Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5b444f8e5 | ||
|
|
8b85d7f646 | ||
|
|
7dcab807d9 | ||
|
|
2819e09e52 | ||
|
|
8ad7903aba | ||
|
|
cc789fc517 | ||
|
|
e65e77f9bf | ||
|
|
70e7743acc | ||
|
|
55f5f2049e | ||
|
|
7f6daef99b | ||
|
|
3006f4d99d | ||
|
|
2a1a4ef9c1 | ||
|
|
5ca2e96f5b | ||
|
|
db55cc6960 | ||
|
|
4c9c79e9f5 |
No files matched your search
@@ -119,5 +119,3 @@ contrib/devtools/split-debug.sh
|
||||
|
||||
.idea
|
||||
cmake-build-*/
|
||||
|
||||
compile_commands\.json
|
||||
@@ -0,0 +1,72 @@
|
||||
stages:
|
||||
- build
|
||||
- test
|
||||
|
||||
.Build Template: &build_template
|
||||
stage: build
|
||||
image: ${BUILD_IMAGE}
|
||||
variables:
|
||||
CCACHE_DIR: ${CI_PROJECT_DIR}/ccache
|
||||
cache:
|
||||
key: ${CI_JOB_NAME}
|
||||
paths:
|
||||
- ${CI_PROJECT_DIR}/ccache
|
||||
artifacts:
|
||||
paths:
|
||||
- src/lbrycrdd
|
||||
- src/lbrycrd-cli
|
||||
- src/lbrycrd-tx
|
||||
- src/test/test_lbrycrd
|
||||
|
||||
Build Linux:
|
||||
<<: *build_template
|
||||
script: packaging/build_linux_64bit.sh
|
||||
|
||||
Build Windows:
|
||||
<<: *build_template
|
||||
artifacts:
|
||||
paths:
|
||||
- src/lbrycrdd.exe
|
||||
- src/lbrycrd-cli.exe
|
||||
- src/lbrycrd-tx.exe
|
||||
- src/test/test_lbrycrd.exe
|
||||
script: packaging/build_windows_64bit.sh
|
||||
|
||||
Build MacOS:
|
||||
<<: *build_template
|
||||
script:
|
||||
- mkdir -p ./depends/SDKs && pushd depends/SDKs && curl -C - ${MAC_OS_SDK} | tar --skip-old-files -xJ && popd
|
||||
- packaging/build_darwin_64bit.sh
|
||||
|
||||
Test Ubuntu:
|
||||
variables:
|
||||
GIT_STRATEGY: none
|
||||
stage: test
|
||||
dependencies: [Build Linux]
|
||||
image: ubuntu:16.04
|
||||
script: src/test/test_lbrycrd
|
||||
|
||||
Test Fedora:
|
||||
variables:
|
||||
GIT_STRATEGY: none
|
||||
stage: test
|
||||
dependencies: [Build Linux]
|
||||
image: fedora:26
|
||||
script: src/test/test_lbrycrd
|
||||
|
||||
Test Windows via Wine:
|
||||
variables:
|
||||
GIT_STRATEGY: none
|
||||
WINEDEBUG: -all
|
||||
stage: test
|
||||
dependencies: [Build Windows]
|
||||
image: jess/wine
|
||||
script: wine src/test/test_lbrycrd.exe
|
||||
|
||||
Test MacOS:
|
||||
variables:
|
||||
GIT_STRATEGY: none
|
||||
stage: test
|
||||
tags: [darwin]
|
||||
dependencies: [Build MacOS]
|
||||
script: src/test/test_lbrycrd
|
||||
+29
-6
@@ -7,6 +7,7 @@ cache:
|
||||
stages:
|
||||
- build
|
||||
- test
|
||||
- quality
|
||||
|
||||
jobs:
|
||||
include:
|
||||
@@ -26,12 +27,24 @@ jobs:
|
||||
script:
|
||||
- docker run -v "$(pwd):/lbrycrd" -v "${HOME}/ccache:/ccache" -w /lbrycrd -e CCACHE_DIR=/ccache ${DOCKER_IMAGE} packaging/build_${NAME}_64bit.sh
|
||||
before_deploy:
|
||||
- mkdir -p dist
|
||||
- sudo zip -Xj dist/lbrycrd-${NAME}.zip src/lbrycrdd${EXT} src/lbrycrd-cli${EXT} src/lbrycrd-tx${EXT}
|
||||
- sudo zip -Xj dist/lbrycrd-${NAME}-test.zip src/test/test_lbrycrd${EXT} src/test/test_lbrycrd_fuzzy${EXT}
|
||||
- mkdir dist
|
||||
- sudo zip -j dist/lbrycrd-${NAME}.zip src/lbrycrdd${EXT} src/lbrycrd-cli${EXT} src/lbrycrd-tx${EXT}
|
||||
- sudo zip -j dist/lbrycrd-${NAME}-test.zip src/test/test_lbrycrd${EXT} src/test/test_lbrycrd_fuzzy${EXT}
|
||||
- sha256sum dist/lbrycrd-${NAME}.zip
|
||||
- sha256sum dist/lbrycrd-${NAME}-test.zip
|
||||
deploy:
|
||||
- provider: releases
|
||||
name: $TRAVIS_BRANCH
|
||||
target_commitish: $TRAVIS_COMMIT
|
||||
tag_name: $TRAVIS_TAG
|
||||
api_key:
|
||||
secure: "Ni5WZNR5CefWXpyDUQLMQbQ2LH4Iot+0SqIoM9c4maW06al1M8vu57vWuj2cESsW7JsaBehCE45Cwmo5kWyEjAiZY8sIMmvixkMP/8uPWuLgNmnIbm7U+d0j652DmZshDYtt8EomqV2RhAx/rmBnzGkruLOw9WTp9ZdBN3WbTt/IpZ2gMgVbGWYGOx+uRw7/yGw8m4gShQheto/dycbyyR3XV2WP9wuLmNYkcQ6JumSoQdDWXcvVfbCwylGq2sLDKwhvfTr4iwYyYsWdmhfdEQl0WcIv5C8xgdiY2vzhi2LmLqFbS/fvKNC26Tfo4bOHFG/eOnvqc+yyEB8B/xqW9Gs+A0TUh/3N30vHYZGcpiDU35DwAN5bZ1+s+mr/ZrNzBJ5BgT8io3g0Ko8gykbDvFQVpg7kxFsqA1YCikEpG86lVGk6clTa5guJvAHse+DfnbWO1nfDxYQXW0md861m0txk8RpTC/TVNyH/lL/vsS7LB67EHhRdZY+O1+5sUGMdtvvhMoxJYCwQGpLkh43KRsKynkMUR94w2O9hc8cknXdV3wrndVz00XNdcur6y4D7HTll1tBrF68CA2yKUSY5hsjtPmdlN+DW8ou/rJiKOpQZ/Xzp69AQEheOFfDPItxQRYxWj0dMOk8eszf0wFvi1N7J/hT/IHnuX5ITfa/T4NE="
|
||||
file: dist/lbrycrd-${NAME}.zip
|
||||
skip_cleanup: true
|
||||
overwrite: true
|
||||
draft: true
|
||||
on:
|
||||
tags: true
|
||||
- provider: s3
|
||||
access_key_id: AKIAICKFHNTR5RITASAQ
|
||||
secret_access_key:
|
||||
@@ -64,10 +77,10 @@ jobs:
|
||||
git:
|
||||
depth: 3
|
||||
install:
|
||||
- mkdir -p testrun && cd testrun
|
||||
- mkdir testrun && cd testrun
|
||||
- curl http://build.lbry.io/lbrycrd/${TRAVIS_BRANCH}/lbrycrd-${NAME}-test.zip -o temp.zip
|
||||
- unzip temp.zip
|
||||
script: TRIEHASH_FUZZER_BLOCKS=1000 ./test_lbrycrd
|
||||
script: ./test_lbrycrd
|
||||
|
||||
- <<: *test-template
|
||||
# os: windows # doesn't support secrets at the moment
|
||||
@@ -78,9 +91,19 @@ jobs:
|
||||
- docker
|
||||
script:
|
||||
- docker pull $DOCKER_WINE_IMAGE
|
||||
- docker run -v "$(pwd):/test" -e "WINEDEBUG=-all" -e "TRIEHASH_FUZZER_BLOCKS=1000" -it $DOCKER_WINE_IMAGE wine "/test/test_lbrycrd.exe"
|
||||
- docker run -v "$(pwd):/test" -e "WINEDEBUG=-all" -it $DOCKER_WINE_IMAGE wine "/test/test_lbrycrd.exe"
|
||||
|
||||
- <<: *test-template
|
||||
os: osx
|
||||
osx_image: xcode8.3
|
||||
env: NAME=darwin
|
||||
|
||||
|
||||
- stage: quality
|
||||
name: "check format"
|
||||
os: linux
|
||||
dist: xenial
|
||||
language: minimal
|
||||
install:
|
||||
- sudo apt-get install -y clang-format-3.9
|
||||
script: git diff -U0 origin/master -- '*.h' '*.cpp' | ./contrib/devtools/clang-format-diff.py -p1
|
||||
@@ -0,0 +1,56 @@
|
||||
cmake_minimum_required(VERSION 3.7)
|
||||
project(lbrycrd_clion) # Do not use for full compile. This is for CLion syntax checking only.
|
||||
|
||||
set (CMAKE_CXX_STANDARD 11)
|
||||
|
||||
if(EXISTS "build/boost")
|
||||
set(BOOST_ROOT "build/boost" CACHE PATH "Boost library path")
|
||||
set(Boost_NO_SYSTEM_PATHS on CACHE BOOL "Do not search system for Boost")
|
||||
endif()
|
||||
find_package(Boost REQUIRED COMPONENTS filesystem thread chrono locale)
|
||||
|
||||
file(GLOB sources
|
||||
src/*.h src/*.cpp
|
||||
src/wallet/*.h src/wallet/*.cpp
|
||||
src/support/*.h src/support/*.cpp src/support/allocators/*.h
|
||||
src/script/*.h src/script/*.cpp
|
||||
src/index/*.h src/index/*.cpp
|
||||
src/interfaces/*.h src/interfaces/*.cpp
|
||||
src/primitives/*.h src/primitives/*.cpp
|
||||
src/policy/*.h src/policy/*.cpp
|
||||
src/crypto/*.h src/crypto/*.cpp
|
||||
src/consensus/*.h src/consensus/*.cpp
|
||||
src/compat/*.h src/compat/*.cpp
|
||||
src/rpc/*.h src/rpc/*.cpp
|
||||
)
|
||||
list(FILTER sources EXCLUDE REGEX "src/bitcoin*.cpp$")
|
||||
|
||||
include_directories(${Boost_INCLUDE_DIRS}
|
||||
build/bdb/include
|
||||
build/libevent/include
|
||||
build/openssl/include
|
||||
src/support/allocators
|
||||
src/support
|
||||
src/rpc
|
||||
src/policy
|
||||
src/wallet src/script
|
||||
src/leveldb/helpers/memenv
|
||||
src/leveldb/include
|
||||
src/config
|
||||
src/crypto
|
||||
src/compat
|
||||
src/obj
|
||||
src/univalue/include
|
||||
src/secp256k1/include
|
||||
src/
|
||||
)
|
||||
|
||||
add_compile_definitions(HAVE_CONFIG_H)
|
||||
|
||||
add_executable(lbrycrd-cli src/bitcoin-cli.cpp ${sources})
|
||||
add_executable(lbrycrd-tx src/bitcoin-tx.cpp ${sources})
|
||||
add_executable(lbrycrdd src/bitcoind.cpp ${sources})
|
||||
|
||||
file(GLOB tests src/test/*.cpp src/wallet/test/*.cpp)
|
||||
add_executable(test_lbrycrd ${tests} ${sources})
|
||||
target_include_directories(test_lbrycrd PRIVATE src/test)
|
||||
@@ -1,35 +1,14 @@
|
||||
# LBRYcrd - The LBRY blockchain
|
||||
|
||||
[](https://travis-ci.org/lbryio/lbrycrd)
|
||||
[](https://github.com/lbryio/lbry-desktop/blob/master/LICENSE)
|
||||
|
||||
LBRYcrd uses a blockchain similar to bitcoin's to implement an index and payment system for content on the LBRY network. It is a fork of [bitcoin core](https://github.com/bitcoin/bitcoin). In addition to the libraries used by bitcoin, LBRYcrd also uses [icu4c](https://github.com/unicode-org/icu/tree/master/icu4c).
|
||||
LBRYcrd uses a blockchain similar to bitcoin's to implement an index and payment system for content on the LBRY network. It is a fork of bitcoin core. In addition to the libraries used by bitcoin, LBRYcrd also uses icu4c.
|
||||
|
||||
Please read the [lbry.tech overview](https://lbry.tech/overview) for a general understanding of the LBRY pieces. From there you could read the [LBRY spec](https://spec.lbry.com/) for specifics on the data in the blockchain.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Installation](#installation)
|
||||
2. [Usage](#usage)
|
||||
1. [Examples](#examples)
|
||||
2. [Data directory](#data-directory)
|
||||
3. [Running from Source](#running-from-source)
|
||||
1. [Ubuntu with pulled static dependencies](#ubuntu-with-pulled-static-dependencies)
|
||||
2. [Ubuntu with local shared dependencies](#ubuntu-with-local-shared-dependencies)
|
||||
3. [MacOS (cross-compiled)](<#macos-(cross-compiled)>)
|
||||
4. [MacOS with local shared dependencies](#macos-with-local-shared-dependencies)
|
||||
5. [Windows (cross-compiled)](<#windows-(cross-compiled)>)
|
||||
6. [Use with CLion](#use-with-clion)
|
||||
4. [Contributing](#contributing)
|
||||
- [Testnet](#testnet)
|
||||
5. [Mailing List](#mailing-list)
|
||||
6. [License](#license)
|
||||
7. [Security](#security)
|
||||
8. [Contact](#contact)
|
||||
Please read the [lbry.tech overview](https://lbry.tech/overview) for a general understanding of the LBRY pieces. From there you could read the [LBRY spec](https://spec.lbry.com/) for specifics on the data in the blockchain.
|
||||
|
||||
## Installation
|
||||
|
||||
Latest binaries are available from https://github.com/lbryio/lbrycrd/releases. There is no installation procedure; the CLI binaries will run as-is and will have any uncommon dependencies statically linked into the binary. The QT GUI is not supported. LBRYcrd is distributed as a collection of executable files; traditional installers are not provided.
|
||||
Latest binaries are available from https://github.com/lbryio/lbrycrd/releases. There is no installation procedure; the CLI binaries will run as-is and will have any uncommon dependencies statically linked into the binary. The QT GUI is not supported. LBRYcrd is distributed as a collection of executable files; traditional installers are not provided.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -37,17 +16,16 @@ The `lbrycrdd` executable will start a LBRYcrd node and connect you to the LBRYc
|
||||
to interact with lbrycrdd through the command line. Command-line help for both executables are available through
|
||||
the "--help" flag (e.g. `lbrycrdd --help`). Examples:
|
||||
|
||||
#### Examples
|
||||
#### Examples:
|
||||
|
||||
Run `./lbrycrdd -server -daemon` to start lbrycrdd in the background.
|
||||
|
||||
Run `./lbrycrd-cli -getinfo` to check for some basic information about your LBRYcrd node.
|
||||
Run `./lbrycrd-cli getinfo` to check for some basic information about your LBRYcrd node.
|
||||
|
||||
Run `./lbrycrd-cli help` to get a list of all commands that you can run. To get help on specific commands run `./lbrycrd-cli [command_name] help`
|
||||
|
||||
Test locally:
|
||||
|
||||
```sh
|
||||
```
|
||||
./lbrycrdd -server -regtest -txindex # run this in its own window
|
||||
./lbrycrd-cli -regtest generate 120 # mine 20 spendable coins
|
||||
./lbrycrd-cli -regtest claimname my_name deadbeef 1 # hold a name claim with 1 coin
|
||||
@@ -57,26 +35,24 @@ Test locally:
|
||||
./lbrycrd-cli -regtest stop # kill lbrycrdd
|
||||
rm -fr ~/.lbrycrd/regtest/ # destroy regtest data
|
||||
```
|
||||
|
||||
For further understanding of a "regtest" setup, see the local stack setup instructions here: https://lbry.tech/resources/regtest-setup
|
||||
|
||||
The CLI help is also browsable online at https://lbry.tech/api/blockchain
|
||||
|
||||
#### Data directory
|
||||
#### Data directory:
|
||||
|
||||
Lbrycrdd will use the below default data directories (changeable with -datadir):
|
||||
|
||||
```sh
|
||||
```
|
||||
Windows: %APPDATA%\lbrycrd
|
||||
Mac: ~/Library/Application Support/lbrycrd
|
||||
Unix: ~/.lbrycrd
|
||||
```
|
||||
|
||||
The data directory contains various things such as your default wallet (wallet.dat), debug logs (debug.log), and blockchain data. You can optionally create a configuration file lbrycrd.conf in the default data directory which will be used by default when running lbrycrdd.
|
||||
|
||||
For a list of configuration parameters, run `./lbrycrdd --help`. Below is a sample lbrycrd.conf to enable JSON RPC server on lbrycrdd.
|
||||
|
||||
```sh
|
||||
```
|
||||
rpcuser=lbry
|
||||
rpcpassword=xyz123456790
|
||||
daemon=1
|
||||
@@ -85,19 +61,15 @@ txindex=1
|
||||
```
|
||||
|
||||
## Running from Source
|
||||
|
||||
The easiest way to compile is to utilize the Docker image that contains the necessary compilers: lbry/build_lbrycrd. This will allow you to reproduce the build as made on our build servers. In this sample we map a local lbrycrd folder and a local ccache folder inside the image:
|
||||
```sh
|
||||
The easiest way to compile is to utilize the Docker image that contains the necessary compilers: lbry/build_lbrycrd. This will allow you to reproduce the build as made on our build servers. I this sample we map a local lbrycrd folder and a local ccache folder inside the image:
|
||||
```
|
||||
git clone https://github.com/lbryio/lbrycrd.git
|
||||
cd lbrycrd
|
||||
docker run -v "$(pwd):/lbrycrd" --rm -v "${HOME}/ccache:/ccache" -w /lbrycrd -e CCACHE_DIR=/ccache lbry/build_lbrycrd packaging/build_linux_64bit.sh
|
||||
```
|
||||
|
||||
Some examples of compiling directly:
|
||||
|
||||
#### Ubuntu with pulled static dependencies
|
||||
|
||||
```sh
|
||||
#### Ubuntu with pulled static dependencies:
|
||||
```
|
||||
sudo apt install build-essential git libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates
|
||||
git clone https://github.com/lbryio/lbrycrd.git
|
||||
cd lbrycrd
|
||||
@@ -105,20 +77,16 @@ cd lbrycrd
|
||||
./src/test/test_lbrycrd
|
||||
|
||||
```
|
||||
|
||||
Other Linux distros would be similar. The build shell script is fairly trivial; take a peek at its contents.
|
||||
|
||||
#### Ubuntu with local shared dependencies
|
||||
|
||||
#### Ubuntu with local shared dependencies:
|
||||
Note: using untested dependencies may lead to conflicting results.
|
||||
|
||||
```sh
|
||||
```
|
||||
sudo add-apt-repository ppa:bitcoin/bitcoin
|
||||
sudo apt-get update
|
||||
sudo apt-get install libdb4.8-dev libdb4.8++-dev libicu-dev libssl-dev libevent-dev \
|
||||
sudo apt-get install libdb4.8-dev libdb4.8++-dev libicu-dev libssl-dev libevent-dev \
|
||||
build-essential git libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates \
|
||||
libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-test-dev libboost-thread-dev
|
||||
|
||||
|
||||
# optionally include libminiupnpc-dev libzmq3-dev
|
||||
|
||||
git clone https://github.com/lbryio/lbrycrd.git
|
||||
@@ -129,13 +97,11 @@ make -j$(nproc)
|
||||
./src/lbrycrdd -server ...
|
||||
|
||||
```
|
||||
|
||||
#### MacOS (cross-compiled)
|
||||
|
||||
```sh
|
||||
#### MacOS (cross-compiled):
|
||||
```
|
||||
sudo apt-get install clang llvm git libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates \
|
||||
libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-test-dev libboost-thread-dev
|
||||
|
||||
|
||||
git clone https://github.com/lbryio/lbrycrd.git
|
||||
cd lbrycrd
|
||||
# download MacOS SDK from your favorite source
|
||||
@@ -144,12 +110,9 @@ tar ... extract SDK to depends/SDKs/MacOSX10.11.sdk
|
||||
./packaging/build_darwin_64bit.sh
|
||||
|
||||
```
|
||||
|
||||
Look in packaging/build_darwin_64bit.sh for further understanding.
|
||||
|
||||
#### MacOS with local shared dependencies
|
||||
|
||||
```sh
|
||||
#### MacOS with local shared dependencies:
|
||||
```
|
||||
brew install boost berkeley-db@4 icu4c libevent
|
||||
# fix conflict with gawk pulled first:
|
||||
brew reinstall readline
|
||||
@@ -164,17 +127,14 @@ CONFIG_SITE=$(pwd)/depends/x86_64-apple-darwin15.6.0/share/config.site ./configu
|
||||
make -j$(sysctl -n hw.ncpu)
|
||||
|
||||
```
|
||||
|
||||
#### Windows (cross-compiled)
|
||||
|
||||
#### Windows (cross-compiled):
|
||||
Compiling on MS Windows (outside of WSL) is not supported. The Windows build is cross-compiled from Linux like so:
|
||||
|
||||
```sh
|
||||
```
|
||||
sudo apt-get install build-essential git libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates \
|
||||
g++-mingw-w64-x86-64 mingw-w64-x86-64-dev
|
||||
|
||||
|
||||
update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix
|
||||
|
||||
|
||||
git clone https://github.com/lbryio/lbrycrd.git
|
||||
cd lbrycrd
|
||||
./packaging/build_windows_64bit.sh
|
||||
@@ -183,18 +143,6 @@ cd lbrycrd
|
||||
|
||||
If you encounter any errors, please check `doc/build-*.md` for further instructions. If you're still stuck, [create an issue](https://github.com/lbryio/lbrycrd/issues/new) with the output of that command, your system info, and any other information you think might be helpful. The scripts in the packaging folder are simple and will grant extra light on the build process as needed.
|
||||
|
||||
#### Use with CLion
|
||||
|
||||
CLion has not traditionally supported Autotools projects, although some progress on that is now in the works. We do include a cmake build file for compiling lbrycrd. See contrib/cmake. Alas, CLion doesn't support external projects in cmake, so that particular approach is also insufficient. CLion does support "compile_commands.json" projects. Fortunately, this can be easily generated for lbrycrd like so:
|
||||
|
||||
```sh
|
||||
pip install --user compiledb
|
||||
./autogen.sh && ./configure --enable-static=no --enable-shared --with-pic --without-gui CXXFLAGS="-O0 -g" CFLAGS="-O0 -g" # or whatever normal lbrycrd config
|
||||
compiledb make -j10
|
||||
```
|
||||
|
||||
Then open the newly generated compile_commands.json file as a project in CLion. Debugging is supported if you compiled with `-g`. To enable that you will need to create a target in CLion by going to File -> Settings -> Build -> Custom Build Targets. Add an empty target with your choice of name. From there you can go to "Edit Configurations", typically found in a drop-down at the top of the editor. Add a Custom Build Application, select your new target, select the compiled file (i.e. test_lbrycrd or lbrycrdd, etc), and then add any necessary command line parameters. Ensure that there is nothing in the "Before launch" section.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions to this project are welcome, encouraged, and compensated. For more details, see [https://lbry.tech/contribute](https://lbry.tech/contribute)
|
||||
@@ -210,8 +158,8 @@ regularly to indicate new official, stable release versions.
|
||||
Testing and code review is the bottleneck for development; we get more pull
|
||||
requests than we can review and test on short notice. Please be patient and help out by testing
|
||||
other people's pull requests, and remember this is a security-critical project where any mistake might cost people
|
||||
lots of money. Developers are strongly encouraged to write [unit tests](/src/test/README.md) for new code and to
|
||||
submit new unit tests for old code. Unit tests are compiled by default and can be run with `src/test/test_lbrycrd`
|
||||
lots of money. Developers are strongly encouraged to write [unit tests](/doc/unit-tests.md) for new code and to
|
||||
submit new unit tests for old code. Unit tests are compiled by default and can be run with `src/test/test_lbrycrd`.
|
||||
|
||||
The Travis CI system makes sure that every pull request is built, and that unit and sanity tests are automatically run. See https://travis-ci.org/lbryio/lbrycrd
|
||||
|
||||
@@ -219,25 +167,17 @@ The Travis CI system makes sure that every pull request is built, and that unit
|
||||
|
||||
Testnet is maintained for testing purposes and can be accessed using the command `./lbrycrdd -testnet`. If you would like to obtain testnet credits, please contact brannon@lbry.com or grin@lbry.com .
|
||||
|
||||
It is easy to solo mine on testnet. (It's easy on mainnet too, but much harder to win.) For instructions see [SGMiner](https://github.com/lbryio/sgminer-gm) and [Mining Contributions](https://github.com/lbryio/lbrycrd/tree/master/contrib/mining)
|
||||
|
||||
## Mailing List
|
||||
|
||||
We maintain a mailing list for notifications of upgrades, security issues, and soft/hard forks. To join, visit [https://lbry.com/forklist](https://lbry.com/forklist).
|
||||
|
||||
## Mailing List
|
||||
|
||||
We maintain a mailing list for notifications of upgrades, security issues, and soft/hard forks. To join, visit [https://lbry.com/forklist](https://lbry.com/forklist).
|
||||
|
||||
## License
|
||||
|
||||
This project is MIT licensed. For the full license, see [LICENSE](LICENSE).
|
||||
|
||||
## Security
|
||||
|
||||
We take security seriously. Please contact [security@lbry.com](mailto:security@lbry.com) regarding any security issues.
|
||||
We take security seriously. Please contact security@lbry.com regarding any security issues.
|
||||
Our PGP key is [here](https://keybase.io/lbry/key.asc) if you need it.
|
||||
|
||||
## Contact
|
||||
|
||||
The primary contact for this project is [@BrannonKing](https://github.com/BrannonKing) (brannon@lbry.com)
|
||||
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ export LC_ALL=C
|
||||
set -e
|
||||
srcdir="$(dirname $0)"
|
||||
cd "$srcdir"
|
||||
if [ -z ${LIBTOOLIZE} ] && GLIBTOOLIZE="$(which glibtoolize 2>/dev/null)"; then
|
||||
if [ -z ${LIBTOOLIZE} ] && GLIBTOOLIZE="`which glibtoolize 2>/dev/null`"; then
|
||||
LIBTOOLIZE="${GLIBTOOLIZE}"
|
||||
export LIBTOOLIZE
|
||||
fi
|
||||
|
||||
@@ -12,7 +12,7 @@ function HELP {
|
||||
echo "-q: compile the QT GUI (not working at present)"
|
||||
echo "-d: force a rebuild of dependencies"
|
||||
echo "-u: run the unit tests when done"
|
||||
echo "-g: compile in debug mode"
|
||||
echo "-g: include debug symbols"
|
||||
echo "-h: show help"
|
||||
exit 1
|
||||
}
|
||||
@@ -56,18 +56,16 @@ done
|
||||
|
||||
echo "Compiling with ${PARALLEL_JOBS} jobs in parallel."
|
||||
|
||||
BUILD_FLAGS=(CXXFLAGS="-O3 -march=native -g")
|
||||
DEBUG_DEPENDS=""
|
||||
BUILD_FLAGS=(CXXFLAGS="-O3 -march=native")
|
||||
if test "$COMPILE_WITH_DEBUG" = true; then
|
||||
BUILD_FLAGS=(--with-debug CXXFLAGS="-O0 -g")
|
||||
DEBUG_DEPENDS="DEBUG=1"
|
||||
BUILD_FLAGS=(--with-debug CXXFLAGS="-Og -g")
|
||||
fi
|
||||
|
||||
cd depends
|
||||
if test "$REBUILD_DEPENDENCIES" = true; then
|
||||
make clean
|
||||
fi
|
||||
make -j${PARALLEL_JOBS} ${DO_NOT_COMPILE_THE_GUI} ${DEBUG_DEPENDS} V=1
|
||||
make -j${PARALLEL_JOBS} ${DO_NOT_COMPILE_THE_GUI} V=1
|
||||
cd ..
|
||||
|
||||
LC_ALL=C autoreconf --install
|
||||
@@ -81,4 +79,4 @@ fi
|
||||
|
||||
if test $? -eq 0 && "$RUN_UNIT_TESTS" = true; then
|
||||
./src/test/test_lbrycrd
|
||||
fi
|
||||
fi
|
||||
+7
-16
@@ -2,8 +2,8 @@ dnl require autoconf 2.60 (AS_ECHO/AS_ECHO_N)
|
||||
AC_PREREQ([2.60])
|
||||
define(_CLIENT_VERSION_MAJOR, 0)
|
||||
define(_CLIENT_VERSION_MINOR, 17)
|
||||
define(_CLIENT_VERSION_REVISION, 4)
|
||||
define(_CLIENT_VERSION_BUILD, 1)
|
||||
define(_CLIENT_VERSION_REVISION, 1)
|
||||
define(_CLIENT_VERSION_BUILD, 0)
|
||||
define(_CLIENT_VERSION_IS_RELEASE, true)
|
||||
define(_COPYRIGHT_YEAR, 2019)
|
||||
define(_COPYRIGHT_HOLDERS,[The %s developers])
|
||||
@@ -14,8 +14,6 @@ AC_CONFIG_HEADERS([src/config/bitcoin-config.h])
|
||||
AC_CONFIG_AUX_DIR([build-aux])
|
||||
AC_CONFIG_MACRO_DIR([build-aux/m4])
|
||||
|
||||
AC_DISABLE_STATIC(yes)
|
||||
|
||||
BITCOIN_DAEMON_NAME=lbrycrdd
|
||||
BITCOIN_GUI_NAME=lbrycrd-qt
|
||||
BITCOIN_CLI_NAME=lbrycrd-cli
|
||||
@@ -62,8 +60,8 @@ case $host in
|
||||
lt_cv_deplibs_check_method="pass_all"
|
||||
;;
|
||||
esac
|
||||
dnl Require C++14 compiler (no GNU extensions)
|
||||
AX_CXX_COMPILE_STDCXX([14], [noext], [mandatory], [nodefault])
|
||||
dnl Require C++11 compiler (no GNU extensions)
|
||||
AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory], [nodefault])
|
||||
dnl Check if -latomic is required for <std::atomic>
|
||||
CHECK_ATOMIC
|
||||
|
||||
@@ -556,7 +554,6 @@ case $host in
|
||||
*linux*)
|
||||
TARGET_OS=linux
|
||||
LEVELDB_TARGET_FLAGS="-DOS_LINUX"
|
||||
AS_IF([test "x${enable_static}" = "xyes"], [LIBTOOL_APP_LDFLAGS="$LIBTOOL_APP_LDFLAGS -all-static"])
|
||||
;;
|
||||
*kfreebsd*)
|
||||
LEVELDB_TARGET_FLAGS="-DOS_KFREEBSD"
|
||||
@@ -592,7 +589,6 @@ if test x$use_pkgconfig = xyes; then
|
||||
AC_MSG_ERROR(pkg-config not found.)
|
||||
fi
|
||||
])
|
||||
AS_IF([test "x${enable_static}" = "xyes"], [PKG_CONFIG="$PKG_CONFIG --static"])
|
||||
fi
|
||||
|
||||
if test x$use_extended_functional_tests != xno; then
|
||||
@@ -650,7 +646,7 @@ if test x$ac_cv_sys_large_files != x &&
|
||||
CPPFLAGS="$CPPFLAGS -D_LARGE_FILES=$ac_cv_sys_large_files"
|
||||
fi
|
||||
|
||||
AS_IF([test x$enable_static = xyes && test x$LDFLAGS != xdarwin], [
|
||||
AS_IF([test x$enable_static != x && test x$LDFLAGS != xdarwin], [
|
||||
# darwin should be using -stdlib=libc++ (and may need a -static instead)
|
||||
AX_CHECK_LINK_FLAG([[-static-libstdc++]], [LDFLAGS="$LDFLAGS -static-libstdc++"])
|
||||
])
|
||||
@@ -707,10 +703,6 @@ if test x$TARGET_OS != xwindows; then
|
||||
AX_CHECK_COMPILE_FLAG([-fPIC],[PIC_FLAGS="-fPIC"])
|
||||
fi
|
||||
|
||||
# All versions of gcc that we commonly use for building are subject to bug
|
||||
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90348. To work around that, set
|
||||
# -fstack-reuse=none for all gcc builds. (Only gcc understands this flag)
|
||||
AX_CHECK_COMPILE_FLAG([-fstack-reuse=none],[HARDENED_CXXFLAGS="$HARDENED_CXXFLAGS -fstack-reuse=none"])
|
||||
if test x$use_hardening != xno; then
|
||||
use_hardening=yes
|
||||
|
||||
@@ -1088,8 +1080,8 @@ AS_IF([test "x${prefix}" != "xNONE" && test "x$ICU_PREFIX" == "xauto"], [
|
||||
])
|
||||
|
||||
AS_IF([test "x$ICU_PREFIX" != "xauto"], [
|
||||
ICU_CPPFLAGS="$(PKG_CONFIG_SYSROOT_DIR=/ PKG_CONFIG_LIBDIR=$ICU_PREFIX/lib/pkgconfig PKG_CONFIG_PATH=$ICU_PREFIX/share/pkgconfig ${PKG_CONFIG} icu-io icu-uc icu-i18n --cflags)"
|
||||
ICU_LIBS="$(PKG_CONFIG_SYSROOT_DIR=/ PKG_CONFIG_LIBDIR=$ICU_PREFIX/lib/pkgconfig PKG_CONFIG_PATH=$ICU_PREFIX/share/pkgconfig ${PKG_CONFIG} icu-io icu-uc icu-i18n --libs)"
|
||||
ICU_CPPFLAGS="$(PKG_CONFIG_SYSROOT_DIR=/ PKG_CONFIG_LIBDIR=$ICU_PREFIX/lib/pkgconfig PKG_CONFIG_PATH=$ICU_PREFIX/share/pkgconfig pkg-config icu-io icu-uc icu-i18n --cflags)"
|
||||
ICU_LIBS="$(PKG_CONFIG_SYSROOT_DIR=/ PKG_CONFIG_LIBDIR=$ICU_PREFIX/lib/pkgconfig PKG_CONFIG_PATH=$ICU_PREFIX/share/pkgconfig pkg-config icu-io icu-uc icu-i18n --libs)"
|
||||
])
|
||||
|
||||
if test x$use_pkgconfig = xyes; then
|
||||
@@ -1509,7 +1501,6 @@ esac
|
||||
|
||||
echo
|
||||
echo "Options used to compile and link:"
|
||||
echo " static link = $enable_static"
|
||||
echo " with wallet = $enable_wallet"
|
||||
echo " with gui / qt = $bitcoin_enable_qt"
|
||||
if test x$bitcoin_enable_qt != xno; then
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
project(lbrycrd)
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
|
||||
include(cmake/CPM.cmake)
|
||||
include(ExternalProject)
|
||||
|
||||
set(OPTIONS "" CACHE STRING "lbrycrdd configure options")
|
||||
set(CPPFLAGS "" CACHE STRING "lbrycrdd compiler options")
|
||||
set(LDFLAGS "" CACHE STRING "lbrycrdd linker options")
|
||||
set(DISABLE_TESTS OFF CACHE BOOL "compilation without tests")
|
||||
set(DISABLE_WALLET OFF CACHE BOOL "compilation without wallet support")
|
||||
set(DISABLE_BENCH OFF CACHE BOOL "compilation without bench support")
|
||||
|
||||
if(NOT ${CPM_USE_LOCAL_PACKAGES})
|
||||
set(OPTIONS "${OPTIONS} --enable-static --disable-shared")
|
||||
else()
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
|
||||
endif()
|
||||
|
||||
set(OPTIONS "--without-gui ${OPTIONS} --with-pic")
|
||||
|
||||
if (${DISABLE_TESTS})
|
||||
set(OPTIONS "${OPTIONS} --disable-tests")
|
||||
endif()
|
||||
|
||||
if (${DISABLE_WALLET})
|
||||
set(OPTIONS "${OPTIONS} --disable-wallet")
|
||||
endif()
|
||||
|
||||
if (${DISABLE_BENCH})
|
||||
set(OPTIONS "${OPTIONS} --disable-bench")
|
||||
endif()
|
||||
|
||||
string(TOLOWER ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR} ARCH)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME OpenSSL
|
||||
GITHUB_REPOSITORY openssl/openssl
|
||||
VERSION 1.0.2
|
||||
GIT_TAG OpenSSL_1_0_2r
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
if(OpenSSL_ADDED)
|
||||
ExternalProject_Add(OpenSSL
|
||||
PREFIX openssl
|
||||
SOURCE_DIR ${OpenSSL_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${OpenSSL_SOURCE_DIR}/Configure ${ARCH} no-shared no-dso no-engines -fPIC --prefix=<INSTALL_DIR>
|
||||
BUILD_IN_SOURCE 1
|
||||
)
|
||||
set(DEPENDS ${DEPENDS} OpenSSL)
|
||||
ExternalProject_Get_Property(OpenSSL INSTALL_DIR)
|
||||
set(LDFLAGS "${LDFLAGS} -L${INSTALL_DIR}/lib")
|
||||
set(CPPFLAGS "${CPPFLAGS} -I${INSTALL_DIR}/include")
|
||||
set(OPENSSL_CPPFLAGS "CPPFLAGS=-I${INSTALL_DIR}/include")
|
||||
set(OPENSSL_LDFLAGS "LDFLAGS=-L${INSTALL_DIR}/lib")
|
||||
endif(OpenSSL_ADDED)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME Libevent
|
||||
GITHUB_REPOSITORY libevent/libevent
|
||||
VERSION 2.1.8
|
||||
GIT_TAG release-2.1.8-stable
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
if(Libevent_ADDED)
|
||||
ExternalProject_Add(Libevent
|
||||
PREFIX libevent
|
||||
DEPENDS ${DEPENDS}
|
||||
SOURCE_DIR ${Libevent_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${Libevent_SOURCE_DIR}/autogen.sh
|
||||
&& ${Libevent_SOURCE_DIR}/configure ${OPENSSL_CPPFLAGS} --enable-cxx --disable-shared --with-pic ${OPENSSL_LDFLAGS} --prefix=<INSTALL_DIR>
|
||||
BUILD_IN_SOURCE 1
|
||||
)
|
||||
set(DEPENDS ${DEPENDS} Libevent)
|
||||
ExternalProject_Get_Property(Libevent INSTALL_DIR)
|
||||
set(LDFLAGS "${LDFLAGS} -L${INSTALL_DIR}/lib")
|
||||
set(CPPFLAGS "${CPPFLAGS} -I${INSTALL_DIR}/include")
|
||||
endif(Libevent_ADDED)
|
||||
|
||||
if(NOT ${DISABLE_WALLET})
|
||||
CPMAddPackage(
|
||||
NAME BerkeleyDB
|
||||
VERSION 4.8.30
|
||||
URL https://download.oracle.com/berkeley-db/db-4.8.30.NC.zip
|
||||
URL_HASH SHA256=43ecd76886992ea416fdadc54b7f2b83ef249d9a6964bd07708ccae42d0226ce
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
if(NOT ${BerkeleyDB_VERSION} VERSION_LESS "5.0")
|
||||
set(OPTIONS "${OPTIONS} --with-incompatible-bdb")
|
||||
endif()
|
||||
|
||||
if(BerkeleyDB_ADDED)
|
||||
ExternalProject_Add(BerkeleyDB
|
||||
PREFIX bdb
|
||||
SOURCE_DIR ${BerkeleyDB_SOURCE_DIR}
|
||||
PATCH_COMMAND sed -i "s/__atomic_compare_exchange/__atomic_compare_exchange_db/" ${BerkeleyDB_SOURCE_DIR}/dbinc/atomic.h
|
||||
CONFIGURE_COMMAND ${BerkeleyDB_SOURCE_DIR}/dist/configure --enable-cxx --disable-shared --with-pic --prefix=<INSTALL_DIR>
|
||||
)
|
||||
set(DEPENDS ${DEPENDS} BerkeleyDB)
|
||||
ExternalProject_Get_Property(BerkeleyDB INSTALL_DIR)
|
||||
set(LDFLAGS "${LDFLAGS} -L${INSTALL_DIR}/lib")
|
||||
set(CPPFLAGS "${CPPFLAGS} -I${INSTALL_DIR}/include")
|
||||
endif(BerkeleyDB_ADDED)
|
||||
endif()
|
||||
|
||||
set(BOOST_LIBS chrono,filesystem,system,locale,thread)
|
||||
|
||||
string(REPLACE "," ";" BOOST_COMPONENTS ${BOOST_LIBS})
|
||||
|
||||
if(NOT ${DISABLE_TESTS})
|
||||
set(BOOST_LIBS ${BOOST_LIBS},test)
|
||||
set(BOOST_COMPONENTS ${BOOST_COMPONENTS};unit_test_framework)
|
||||
endif()
|
||||
|
||||
CPMAddPackage(
|
||||
NAME Boost
|
||||
GITHUB_REPOSITORY boostorg/boost
|
||||
VERSION 1.64.0
|
||||
COMPONENTS ${BOOST_COMPONENTS}
|
||||
GIT_TAG boost-1.69.0
|
||||
GIT_SUBMODULES libs/* tools/*
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
# if boost is found system wide we expect to be compiled against icu, so we can skip it
|
||||
if(Boost_ADDED)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME ICU
|
||||
GITHUB_REPOSITORY unicode-org/icu
|
||||
VERSION 63.2
|
||||
GIT_TAG release-63-2
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
if(ICU_ADDED)
|
||||
ExternalProject_Add(ICU
|
||||
PREFIX icu
|
||||
SOURCE_DIR ${ICU_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${ICU_SOURCE_DIR}/icu4c/source/configure --disable-extras --disable-strict --enable-static
|
||||
--disable-shared --disable-tests --disable-samples --disable-dyload --disable-layoutex CFLAGS=-fPIC CPPFLAGS=-fPIC --prefix=<INSTALL_DIR>
|
||||
)
|
||||
set(DEPENDS ${DEPENDS} ICU)
|
||||
ExternalProject_Get_Property(ICU INSTALL_DIR)
|
||||
set(ICU_PATH ${INSTALL_DIR})
|
||||
set(OPTIONS "${OPTIONS} --with-icu=${ICU_PATH}")
|
||||
set(LDFLAGS "${LDFLAGS} -L${ICU_PATH}/lib")
|
||||
set(CPPFLAGS "${CPPFLAGS} -I${ICU_PATH}/include")
|
||||
endif(ICU_ADDED)
|
||||
|
||||
ExternalProject_Add(Boost
|
||||
PREFIX boost
|
||||
DEPENDS ${DEPENDS}
|
||||
SOURCE_DIR ${Boost_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${Boost_SOURCE_DIR}/bootstrap.sh --with-icu=${ICU_PATH} --with-libraries=${BOOST_LIBS} && ${Boost_SOURCE_DIR}/b2 headers
|
||||
BUILD_COMMAND ${Boost_SOURCE_DIR}/b2 install threading=multi -sNO_BZIP2=1 -sNO_ZLIB=1 link=static linkflags="-L${ICU_PATH}/lib -licuio -licuuc -licudata -licui18n" cxxflags=-fPIC boost.locale.iconv=off boost.locale.posix=off boost.locale.icu=on boost.locale.std=off -sICU_PATH=${ICU_PATH} --prefix=<INSTALL_DIR>
|
||||
INSTALL_COMMAND ""
|
||||
BUILD_IN_SOURCE 1
|
||||
)
|
||||
set(DEPENDS ${DEPENDS} Boost)
|
||||
ExternalProject_Get_Property(Boost INSTALL_DIR)
|
||||
set(OPTIONS "${OPTIONS} --with-boost=${INSTALL_DIR}")
|
||||
set(LDFLAGS "${LDFLAGS} -L${INSTALL_DIR}/lib")
|
||||
set(CPPFLAGS "${CPPFLAGS} -I${INSTALL_DIR}/include")
|
||||
set_property(DIRECTORY PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${Boost_SOURCE_DIR}/bin.v2)
|
||||
endif(Boost_ADDED)
|
||||
|
||||
set(CPPFLAGS "${CPPFLAGS} -Wno-parentheses -Wno-unused-local-typedefs -Wno-deprecated -Wno-implicit-fallthrough -Wno-unused-parameter")
|
||||
|
||||
separate_arguments(OPTIONS)
|
||||
|
||||
ExternalProject_Add(lbrycrdd
|
||||
PREFIX lbrycrdd
|
||||
DEPENDS ${DEPENDS}
|
||||
SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../..
|
||||
CONFIGURE_COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/../../autogen.sh
|
||||
&& ${CMAKE_CURRENT_SOURCE_DIR}/../../configure ${OPTIONS} CPPFLAGS=${CPPFLAGS} LDFLAGS=${LDFLAGS} --prefix=<INSTALL_DIR>
|
||||
BUILD_IN_SOURCE 1
|
||||
BUILD_ALWAYS 1
|
||||
)
|
||||
@@ -1,210 +0,0 @@
|
||||
# TheLartians/CPM - A simple Git dependency manager
|
||||
# =================================================
|
||||
# See https://github.com/TheLartians/CPM for usage and update instructions.
|
||||
#
|
||||
# MIT License
|
||||
# -----------
|
||||
#[[
|
||||
Copyright (c) 2019 Lars Melchior
|
||||
|
||||
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.
|
||||
]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
|
||||
|
||||
set(CURRENT_CPM_VERSION 0.11.1)
|
||||
|
||||
if(CPM_DIRECTORY)
|
||||
if(NOT ${CPM_DIRECTORY} MATCHES ${CMAKE_CURRENT_LIST_DIR})
|
||||
if (${CPM_VERSION} VERSION_LESS ${CURRENT_CPM_VERSION})
|
||||
CPM_HANDLE_OLD_VERSION(${CURRENT_CPM_VERSION})
|
||||
endif()
|
||||
return()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(CPM_VERSION ${CURRENT_CPM_VERSION} CACHE INTERNAL "")
|
||||
set(CPM_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} CACHE INTERNAL "")
|
||||
set(CPM_PACKAGES "" CACHE INTERNAL "")
|
||||
|
||||
option(CPM_USE_LOCAL_PACKAGES "Use locally installed packages (find_package)" ON)
|
||||
option(CPM_LOCAL_PACKAGES_ONLY "Use only locally installed packages" OFF)
|
||||
|
||||
include(FetchContent)
|
||||
include(CMakeParseArguments)
|
||||
|
||||
# Initialize logging prefix
|
||||
if(NOT CPM_INDENT)
|
||||
set(CPM_INDENT "CPM:")
|
||||
endif()
|
||||
|
||||
# The main workhorse of CPM
|
||||
function(CPMAddPackage)
|
||||
|
||||
set(oneValueArgs
|
||||
NAME
|
||||
VERSION
|
||||
GIT_TAG
|
||||
DOWNLOAD_ONLY
|
||||
GITHUB_REPOSITORY
|
||||
GITLAB_REPOSITORY
|
||||
)
|
||||
|
||||
set(multiValueArgs
|
||||
OPTIONS
|
||||
COMPONENTS
|
||||
)
|
||||
|
||||
cmake_parse_arguments(CPM_ARGS "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
|
||||
|
||||
if(${CPM_USE_LOCAL_PACKAGES} OR ${CPM_LOCAL_PACKAGES_ONLY})
|
||||
find_package(${CPM_ARGS_NAME} ${CPM_ARGS_VERSION} OPTIONAL_COMPONENTS ${CPM_ARGS_COMPONENTS} QUIET)
|
||||
|
||||
if(${CPM_ARGS_NAME}_FOUND)
|
||||
message(STATUS "CPM: adding local package ${CPM_ARGS_NAME}@${${CPM_ARGS_NAME}_VERSION}")
|
||||
set(${CPM_ARGS_NAME}_VERSION "${${CPM_ARGS_NAME}_VERSION}" PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(${CPM_LOCAL_PACKAGES_ONLY})
|
||||
message(SEND_ERROR "CPM: ${CPM_ARGS_NAME} not found via find_package(${CPM_ARGS_NAME} ${CPM_ARGS_VERSION})")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if (NOT CPM_ARGS_VERSION)
|
||||
set(CPM_ARGS_VERSION 0)
|
||||
endif()
|
||||
|
||||
if (NOT CPM_ARGS_GIT_TAG)
|
||||
set(CPM_ARGS_GIT_TAG v${CPM_ARGS_VERSION})
|
||||
endif()
|
||||
|
||||
list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_TAG ${CPM_ARGS_GIT_TAG})
|
||||
|
||||
if(CPM_ARGS_DOWNLOAD_ONLY)
|
||||
set(DOWNLOAD_ONLY ${CPM_ARGS_DOWNLOAD_ONLY})
|
||||
else()
|
||||
set(DOWNLOAD_ONLY NO)
|
||||
endif()
|
||||
|
||||
if (CPM_ARGS_GITHUB_REPOSITORY)
|
||||
list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_REPOSITORY "https://github.com/${CPM_ARGS_GITHUB_REPOSITORY}.git")
|
||||
endif()
|
||||
|
||||
if (CPM_ARGS_GITLAB_REPOSITORY)
|
||||
list(APPEND CPM_ARGS_UNPARSED_ARGUMENTS GIT_REPOSITORY "https://gitlab.com/${CPM_ARGS_GITLAB_REPOSITORY}.git")
|
||||
endif()
|
||||
|
||||
if (${CPM_ARGS_NAME} IN_LIST CPM_PACKAGES)
|
||||
CPM_GET_PACKAGE_VERSION(${CPM_ARGS_NAME})
|
||||
if(${CPM_PACKAGE_VERSION} VERSION_LESS ${CPM_ARGS_VERSION})
|
||||
message(WARNING "${CPM_INDENT} requires a newer version of ${CPM_ARGS_NAME} (${CPM_ARGS_VERSION}) than currently included (${CPM_PACKAGE_VERSION}).")
|
||||
endif()
|
||||
if (CPM_ARGS_OPTIONS)
|
||||
foreach(OPTION ${CPM_ARGS_OPTIONS})
|
||||
CPM_PARSE_OPTION(${OPTION})
|
||||
if(NOT "${${OPTION_KEY}}" STREQUAL ${OPTION_VALUE})
|
||||
message(WARNING "${CPM_INDENT} ignoring package option for ${CPM_ARGS_NAME}: ${OPTION_KEY} = ${OPTION_VALUE} (${${OPTION_KEY}})")
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
CPM_FETCH_PACKAGE(${CPM_ARGS_NAME} ${DOWNLOAD_ONLY})
|
||||
CPMGetProperties(${CPM_ARGS_NAME})
|
||||
set(${CPM_ARGS_NAME}_VERSION ${CPM_ARGS_VERSION} PARENT_SCOPE)
|
||||
set(${CPM_ARGS_NAME}_SOURCE_DIR "${${CPM_ARGS_NAME}_SOURCE_DIR}" PARENT_SCOPE)
|
||||
set(${CPM_ARGS_NAME}_BINARY_DIR "${${CPM_ARGS_NAME}_BINARY_DIR}" PARENT_SCOPE)
|
||||
set(${CPM_ARGS_NAME}_ADDED NO PARENT_SCOPE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
CPMRegisterPackage(${CPM_ARGS_NAME} ${CPM_ARGS_VERSION})
|
||||
|
||||
if (CPM_ARGS_OPTIONS)
|
||||
foreach(OPTION ${CPM_ARGS_OPTIONS})
|
||||
CPM_PARSE_OPTION(${OPTION})
|
||||
set(${OPTION_KEY} ${OPTION_VALUE} CACHE INTERNAL "")
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
CPM_DECLARE_PACKAGE(${CPM_ARGS_NAME} ${CPM_ARGS_VERSION} ${CPM_ARGS_GIT_TAG} "${CPM_ARGS_UNPARSED_ARGUMENTS}")
|
||||
CPM_FETCH_PACKAGE(${CPM_ARGS_NAME} ${DOWNLOAD_ONLY})
|
||||
CPMGetProperties(${CPM_ARGS_NAME})
|
||||
set(${CPM_ARGS_NAME}_VERSION ${CPM_ARGS_VERSION} PARENT_SCOPE)
|
||||
set(${CPM_ARGS_NAME}_SOURCE_DIR "${${CPM_ARGS_NAME}_SOURCE_DIR}" PARENT_SCOPE)
|
||||
set(${CPM_ARGS_NAME}_BINARY_DIR "${${CPM_ARGS_NAME}_BINARY_DIR}" PARENT_SCOPE)
|
||||
set(${CPM_ARGS_NAME}_ADDED YES PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function (CPM_DECLARE_PACKAGE PACKAGE VERSION GIT_TAG)
|
||||
message(STATUS "${CPM_INDENT} adding package ${PACKAGE}@${VERSION} (${GIT_TAG})")
|
||||
|
||||
FetchContent_Declare(
|
||||
${PACKAGE}
|
||||
${ARGN}
|
||||
)
|
||||
endfunction()
|
||||
|
||||
function (CPM_FETCH_PACKAGE PACKAGE DOWNLOAD_ONLY)
|
||||
set(CPM_OLD_INDENT "${CPM_INDENT}")
|
||||
set(CPM_INDENT "${CPM_INDENT} ${PACKAGE}:")
|
||||
if(${DOWNLOAD_ONLY})
|
||||
if(NOT "${PACKAGE}_POPULATED")
|
||||
FetchContent_Populate(${PACKAGE})
|
||||
endif()
|
||||
else()
|
||||
FetchContent_MakeAvailable(${PACKAGE})
|
||||
endif()
|
||||
set(CPM_INDENT "${CPM_OLD_INDENT}")
|
||||
endfunction()
|
||||
|
||||
function (CPMGetProperties PACKAGE)
|
||||
FetchContent_GetProperties(${PACKAGE})
|
||||
string(TOLOWER ${PACKAGE} lpackage)
|
||||
set(${PACKAGE}_SOURCE_DIR "${${lpackage}_SOURCE_DIR}" PARENT_SCOPE)
|
||||
set(${PACKAGE}_BINARY_DIR "${${lpackage}_BINARY_DIR}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(CPMRegisterPackage PACKAGE VERSION)
|
||||
list(APPEND CPM_PACKAGES ${PACKAGE})
|
||||
set(CPM_PACKAGES ${CPM_PACKAGES} CACHE INTERNAL "")
|
||||
set("CPM_PACKAGE_${PACKAGE}_VERSION" ${VERSION} CACHE INTERNAL "")
|
||||
endfunction()
|
||||
|
||||
function(CPM_GET_PACKAGE_VERSION PACKAGE)
|
||||
set(CPM_PACKAGE_VERSION "${CPM_PACKAGE_${PACKAGE}_VERSION}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function(CPM_PARSE_OPTION OPTION)
|
||||
string(REGEX MATCH "^[^ ]+" OPTION_KEY ${OPTION})
|
||||
string(LENGTH ${OPTION_KEY} OPTION_KEY_LENGTH)
|
||||
math(EXPR OPTION_KEY_LENGTH "${OPTION_KEY_LENGTH}+1")
|
||||
string(SUBSTRING ${OPTION} "${OPTION_KEY_LENGTH}" "-1" OPTION_VALUE)
|
||||
set(OPTION_KEY "${OPTION_KEY}" PARENT_SCOPE)
|
||||
set(OPTION_VALUE "${OPTION_VALUE}" PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
function (CPM_HANDLE_OLD_VERSION NEW_CPM_VERSION)
|
||||
|
||||
message(AUTHOR_WARNING "${CPM_INDENT} \
|
||||
A dependency is using a more recent CPM (${NEW_CPM_VERSION}) than the current project (${CPM_VERSION}). \
|
||||
It is recommended to upgrade CPM to the most recent version. \
|
||||
See https://github.com/TheLartians/CPM for more information."
|
||||
)
|
||||
|
||||
endfunction()
|
||||
@@ -1,171 +0,0 @@
|
||||
# Author: sum01 <sum01@protonmail.com>
|
||||
# Git: https://github.com/sum01/FindBerkeleyDB
|
||||
# Read the README.md for the full info.
|
||||
|
||||
# NOTE: If Berkeley DB ever gets a Pkg-config ".pc" file, add pkg_check_modules() here
|
||||
|
||||
# Checks if environment paths are empty, set them if they aren't
|
||||
if(NOT "$ENV{BERKELEYDB_ROOT}" STREQUAL "")
|
||||
set(_BERKELEYDB_HINTS "$ENV{BERKELEYDB_ROOT}")
|
||||
elseif(NOT "$ENV{Berkeleydb_ROOT}" STREQUAL "")
|
||||
set(_BERKELEYDB_HINTS "$ENV{Berkeleydb_ROOT}")
|
||||
elseif(NOT "$ENV{BERKELEYDBROOT}" STREQUAL "")
|
||||
set(_BERKELEYDB_HINTS "$ENV{BERKELEYDBROOT}")
|
||||
else()
|
||||
# Set just in case, as it's used regardless if it's empty or not
|
||||
set(_BERKELEYDB_HINTS "")
|
||||
endif()
|
||||
|
||||
# Allow user to pass a path instead of guessing
|
||||
if(BerkeleyDB_ROOT_DIR)
|
||||
set(_BERKELEYDB_PATHS "${BerkeleyDB_ROOT_DIR}")
|
||||
elseif(CMAKE_SYSTEM_NAME MATCHES ".*[wW]indows.*")
|
||||
# MATCHES is used to work on any devies with windows in the name
|
||||
# Shameless copy-paste from FindOpenSSL.cmake v3.8
|
||||
file(TO_CMAKE_PATH "$ENV{PROGRAMFILES}" _programfiles)
|
||||
list(APPEND _BERKELEYDB_HINTS "${_programfiles}")
|
||||
|
||||
# There's actually production release and version numbers in the file path.
|
||||
# For example, if they're on v6.2.32: C:/Program Files/Oracle/Berkeley DB 12cR1 6.2.32/
|
||||
# But this still works to find it, so I'm guessing it can accept partial path matches.
|
||||
|
||||
foreach(_TARGET_BERKELEYDB_PATH "Oracle/Berkeley DB" "Berkeley DB")
|
||||
list(APPEND _BERKELEYDB_PATHS
|
||||
"${_programfiles}/${_TARGET_BERKELEYDB_PATH}"
|
||||
"C:/Program Files (x86)/${_TARGET_BERKELEYDB_PATH}"
|
||||
"C:/Program Files/${_TARGET_BERKELEYDB_PATH}"
|
||||
"C:/${_TARGET_BERKELEYDB_PATH}"
|
||||
)
|
||||
endforeach()
|
||||
else()
|
||||
# Paths for anything other than Windows
|
||||
# Cellar/berkeley-db is for macOS from homebrew installation
|
||||
list(APPEND _BERKELEYDB_PATHS
|
||||
"/usr"
|
||||
"/usr/local"
|
||||
"/usr/local/Cellar/berkeley-db"
|
||||
"/opt"
|
||||
"/opt/local"
|
||||
)
|
||||
endif()
|
||||
|
||||
# Find includes path
|
||||
find_path(BerkeleyDB_INCLUDE_DIRS
|
||||
NAMES "db.h"
|
||||
HINTS ${_BERKELEYDB_HINTS}
|
||||
PATH_SUFFIXES "include" "includes"
|
||||
PATHS ${_BERKELEYDB_PATHS}
|
||||
)
|
||||
|
||||
# Checks if the version file exists, save the version file to a var, and fail if there's no version file
|
||||
if(BerkeleyDB_INCLUDE_DIRS)
|
||||
# Read the version file db.h into a variable
|
||||
file(READ "${BerkeleyDB_INCLUDE_DIRS}/db.h" _BERKELEYDB_DB_HEADER)
|
||||
# Parse the DB version into variables to be used in the lib names
|
||||
string(REGEX REPLACE ".*DB_VERSION_MAJOR ([0-9]+).*" "\\1" BerkeleyDB_VERSION_MAJOR "${_BERKELEYDB_DB_HEADER}")
|
||||
string(REGEX REPLACE ".*DB_VERSION_MINOR ([0-9]+).*" "\\1" BerkeleyDB_VERSION_MINOR "${_BERKELEYDB_DB_HEADER}")
|
||||
# Patch version example on non-crypto installs: x.x.xNC
|
||||
string(REGEX REPLACE ".*DB_VERSION_PATCH ([0-9]+(NC)?).*" "\\1" BerkeleyDB_VERSION_PATCH "${_BERKELEYDB_DB_HEADER}")
|
||||
else()
|
||||
if(BerkeleyDB_FIND_REQUIRED)
|
||||
# If the find_package(BerkeleyDB REQUIRED) was used, fail since we couldn't find the header
|
||||
message(FATAL_ERROR "Failed to find Berkeley DB's header file \"db.h\"! Try setting \"BerkeleyDB_ROOT_DIR\" when initiating Cmake.")
|
||||
elseif(NOT BerkeleyDB_FIND_QUIETLY)
|
||||
message(WARNING "Failed to find Berkeley DB's header file \"db.h\"! Try setting \"BerkeleyDB_ROOT_DIR\" when initiating Cmake.")
|
||||
endif()
|
||||
# Set some garbage values to the versions since we didn't find a file to read
|
||||
set(BerkeleyDB_VERSION_MAJOR "0")
|
||||
set(BerkeleyDB_VERSION_MINOR "0")
|
||||
set(BerkeleyDB_VERSION_PATCH "0")
|
||||
endif()
|
||||
|
||||
# The actual returned/output version variable (the others can be used if needed)
|
||||
set(BerkeleyDB_VERSION "${BerkeleyDB_VERSION_MAJOR}.${BerkeleyDB_VERSION_MINOR}.${BerkeleyDB_VERSION_PATCH}")
|
||||
|
||||
# Finds the target library for berkeley db, since they all follow the same naming conventions
|
||||
macro(_berkeleydb_get_lib _BERKELEYDB_OUTPUT_VARNAME _TARGET_BERKELEYDB_LIB)
|
||||
# Different systems sometimes have a version in the lib name...
|
||||
# and some have a dash or underscore before the versions.
|
||||
# CMake recommends to put unversioned names before versioned names
|
||||
find_library(${_BERKELEYDB_OUTPUT_VARNAME}
|
||||
NAMES
|
||||
"${_TARGET_BERKELEYDB_LIB}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}${BerkeleyDB_VERSION_MAJOR}.${BerkeleyDB_VERSION_MINOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}-${BerkeleyDB_VERSION_MAJOR}.${BerkeleyDB_VERSION_MINOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}_${BerkeleyDB_VERSION_MAJOR}.${BerkeleyDB_VERSION_MINOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}${BerkeleyDB_VERSION_MAJOR}${BerkeleyDB_VERSION_MINOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}-${BerkeleyDB_VERSION_MAJOR}${BerkeleyDB_VERSION_MINOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}_${BerkeleyDB_VERSION_MAJOR}${BerkeleyDB_VERSION_MINOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}${BerkeleyDB_VERSION_MAJOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}-${BerkeleyDB_VERSION_MAJOR}"
|
||||
"lib${_TARGET_BERKELEYDB_LIB}_${BerkeleyDB_VERSION_MAJOR}"
|
||||
HINTS ${_BERKELEYDB_HINTS}
|
||||
PATH_SUFFIXES
|
||||
"lib"
|
||||
"lib64"
|
||||
"libs"
|
||||
"libs64"
|
||||
PATHS ${_BERKELEYDB_PATHS}
|
||||
)
|
||||
# If the library was found, add it to our list of libraries
|
||||
if(${_BERKELEYDB_OUTPUT_VARNAME})
|
||||
# If found, append to our libraries variable
|
||||
# The ${{}} is because the first expands to target the real variable, the second expands the variable's contents...
|
||||
# and the real variable's contents is the path to the lib. Thus, it appends the path of the lib to BerkeleyDB_LIBRARIES.
|
||||
list(APPEND BerkeleyDB_LIBRARIES "${${_BERKELEYDB_OUTPUT_VARNAME}}")
|
||||
endif()
|
||||
endmacro()
|
||||
|
||||
# Find and set the paths of the specific library to the variable
|
||||
_berkeleydb_get_lib(BerkeleyDB_LIBRARY "db")
|
||||
# NOTE: Windows doesn't have a db_cxx lib, but instead compiles the cxx code into the "db" lib
|
||||
_berkeleydb_get_lib(BerkeleyDB_Cxx_LIBRARY "db_cxx")
|
||||
# NOTE: I don't think Linux/Unix gets an SQL lib
|
||||
_berkeleydb_get_lib(BerkeleyDB_Sql_LIBRARY "db_sql")
|
||||
_berkeleydb_get_lib(BerkeleyDB_Stl_LIBRARY "db_stl")
|
||||
|
||||
# Needed for find_package_handle_standard_args()
|
||||
include(FindPackageHandleStandardArgs)
|
||||
# Fails if required vars aren't found, or if the version doesn't meet specifications.
|
||||
find_package_handle_standard_args(BerkeleyDB
|
||||
FOUND_VAR BerkeleyDB_FOUND
|
||||
REQUIRED_VARS
|
||||
BerkeleyDB_INCLUDE_DIRS
|
||||
BerkeleyDB_LIBRARY
|
||||
BerkeleyDB_LIBRARIES
|
||||
VERSION_VAR BerkeleyDB_VERSION
|
||||
)
|
||||
|
||||
# Only show the variables in the GUI if they click "advanced".
|
||||
# Does nothing when using the CLI
|
||||
mark_as_advanced(FORCE
|
||||
BerkeleyDB_FOUND
|
||||
BerkeleyDB_INCLUDE_DIRS
|
||||
BerkeleyDB_LIBRARIES
|
||||
BerkeleyDB_VERSION
|
||||
BerkeleyDB_VERSION_MAJOR
|
||||
BerkeleyDB_VERSION_MINOR
|
||||
BerkeleyDB_VERSION_PATCH
|
||||
BerkeleyDB_LIBRARY
|
||||
BerkeleyDB_Cxx_LIBRARY
|
||||
BerkeleyDB_Stl_LIBRARY
|
||||
BerkeleyDB_Sql_LIBRARY
|
||||
)
|
||||
|
||||
# Create an imported lib for easy linking by external projects
|
||||
if(BerkeleyDB_FOUND AND BerkeleyDB_LIBRARIES AND NOT TARGET Oracle::BerkeleyDB)
|
||||
add_library(Oracle::BerkeleyDB UNKNOWN IMPORTED)
|
||||
set_target_properties(Oracle::BerkeleyDB PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${BerkeleyDB_INCLUDE_DIRS}"
|
||||
IMPORTED_LOCATION "${BerkeleyDB_LIBRARY}"
|
||||
INTERFACE_LINK_LIBRARIES "${BerkeleyDB_LIBRARIES}"
|
||||
)
|
||||
endif()
|
||||
|
||||
include(FindPackageMessage)
|
||||
# A message that tells the user what includes/libs were found, and obeys the QUIET command.
|
||||
find_package_message(BerkeleyDB
|
||||
"Found BerkeleyDB libraries: ${BerkeleyDB_LIBRARIES}"
|
||||
"[${BerkeleyDB_LIBRARIES}[${BerkeleyDB_INCLUDE_DIRS}]]"
|
||||
)
|
||||
@@ -1,97 +0,0 @@
|
||||
# - Try to find libevent
|
||||
#.rst
|
||||
# FindLibevent
|
||||
# ------------
|
||||
#
|
||||
# Find Libevent include directories and libraries. Invoke as::
|
||||
#
|
||||
# find_package(Libevent
|
||||
# [version] [EXACT] # Minimum or exact version
|
||||
# [REQUIRED] # Fail if Libevent is not found
|
||||
# [COMPONENT <C>...]) # Libraries to look for
|
||||
#
|
||||
# Valid components are one or more of:: libevent core extra pthreads openssl.
|
||||
# Note that 'libevent' contains both core and extra. You must specify one of
|
||||
# them for the other components.
|
||||
#
|
||||
# This module will define the following variables::
|
||||
#
|
||||
# LIBEVENT_FOUND - True if headers and requested libraries were found
|
||||
# LIBEVENT_INCLUDE_DIRS - Libevent include directories
|
||||
# LIBEVENT_LIBRARIES - Libevent libraries to be linked
|
||||
# LIBEVENT_<C>_FOUND - Component <C> was found (<C> is uppercase)
|
||||
# LIBEVENT_<C>_LIBRARY - Library to be linked for Libevent component <C>.
|
||||
|
||||
find_package(PkgConfig QUIET)
|
||||
pkg_check_modules(PC_LIBEVENT QUIET libevent)
|
||||
|
||||
# Look for the Libevent 2.0 or 1.4 headers
|
||||
find_path(LIBEVENT_INCLUDE_DIR
|
||||
NAMES
|
||||
event2/event-config.h
|
||||
event-config.h
|
||||
HINTS
|
||||
${PC_LIBEVENT_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
if(LIBEVENT_INCLUDE_DIR)
|
||||
set(_version_regex "^#define[ \t]+_EVENT_VERSION[ \t]+\"([^\"]+)\".*")
|
||||
if(EXISTS "${LIBEVENT_INCLUDE_DIR}/event2/event-config.h")
|
||||
# Libevent 2.0
|
||||
file(STRINGS "${LIBEVENT_INCLUDE_DIR}/event2/event-config.h"
|
||||
LIBEVENT_VERSION REGEX "${_version_regex}")
|
||||
if("${LIBEVENT_VERSION}" STREQUAL "")
|
||||
set(LIBEVENT_VERSION ${PC_LIBEVENT_VERSION})
|
||||
endif()
|
||||
else()
|
||||
# Libevent 1.4
|
||||
file(STRINGS "${LIBEVENT_INCLUDE_DIR}/event-config.h"
|
||||
LIBEVENT_VERSION REGEX "${_version_regex}")
|
||||
endif()
|
||||
string(REGEX REPLACE "${_version_regex}" "\\1"
|
||||
LIBEVENT_VERSION "${LIBEVENT_VERSION}")
|
||||
unset(_version_regex)
|
||||
endif()
|
||||
|
||||
set(_LIBEVENT_REQUIRED_VARS)
|
||||
foreach(COMPONENT ${Libevent_FIND_COMPONENTS})
|
||||
set(_LIBEVENT_LIBNAME libevent)
|
||||
# Note: compare two variables to avoid a CMP0054 policy warning
|
||||
if(COMPONENT STREQUAL _LIBEVENT_LIBNAME)
|
||||
set(_LIBEVENT_LIBNAME event)
|
||||
else()
|
||||
set(_LIBEVENT_LIBNAME "event_${COMPONENT}")
|
||||
endif()
|
||||
string(TOUPPER "${COMPONENT}" COMPONENT_UPPER)
|
||||
find_library(LIBEVENT_${COMPONENT_UPPER}_LIBRARY
|
||||
NAMES ${_LIBEVENT_LIBNAME}
|
||||
HINTS ${PC_LIBEVENT_LIBRARY_DIRS}
|
||||
)
|
||||
if(LIBEVENT_${COMPONENT_UPPER}_LIBRARY)
|
||||
set(Libevent_${COMPONENT}_FOUND 1)
|
||||
endif()
|
||||
list(APPEND _LIBEVENT_REQUIRED_VARS LIBEVENT_${COMPONENT_UPPER}_LIBRARY)
|
||||
endforeach()
|
||||
unset(_LIBEVENT_LIBNAME)
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
# handle the QUIETLY and REQUIRED arguments and set LIBEVENT_FOUND to TRUE
|
||||
# if all listed variables are TRUE and the requested version matches.
|
||||
find_package_handle_standard_args(Libevent REQUIRED_VARS
|
||||
${_LIBEVENT_REQUIRED_VARS}
|
||||
LIBEVENT_INCLUDE_DIR
|
||||
VERSION_VAR LIBEVENT_VERSION
|
||||
HANDLE_COMPONENTS)
|
||||
|
||||
if(LIBEVENT_FOUND)
|
||||
set(LIBEVENT_INCLUDE_DIRS ${LIBEVENT_INCLUDE_DIR})
|
||||
set(LIBEVENT_LIBRARIES)
|
||||
foreach(COMPONENT ${Libevent_FIND_COMPONENTS})
|
||||
string(TOUPPER "${COMPONENT}" COMPONENT_UPPER)
|
||||
list(APPEND LIBEVENT_LIBRARIES ${LIBEVENT_${COMPONENT_UPPER}_LIBRARY})
|
||||
set(LIBEVENT_${COMPONENT_UPPER}_FOUND ${Libevent_${COMPONENT}_FOUND})
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
mark_as_advanced(LIBEVENT_INCLUDE_DIR ${_LIBEVENT_REQUIRED_VARS})
|
||||
unset(_LIBEVENT_REQUIRED_VARS)
|
||||
@@ -59,13 +59,12 @@ def get_obj_from_dirty_text(full_object: str):
|
||||
last_name = property_name
|
||||
elif len(left) > 1:
|
||||
match = re.match(r'^(\[)?"(?P<name>\w.*?)"(\])?.*', left)
|
||||
if match is not None:
|
||||
last_name = match.group('name')
|
||||
if match.group(1) is not None and match.group(3) is not None:
|
||||
left = '['
|
||||
property_refined_type = 'string'
|
||||
if 'string' not in line:
|
||||
raise NotImplementedError('Not implemented: ' + line)
|
||||
last_name = match.group('name')
|
||||
if match.group(1) is not None and match.group(3) is not None:
|
||||
left = '['
|
||||
property_refined_type = 'string'
|
||||
if 'string' not in line:
|
||||
raise NotImplementedError('Not implemented: ' + line)
|
||||
|
||||
if left.endswith('['):
|
||||
object_stack.append({'type': 'array', 'items': {'type': property_refined_type}})
|
||||
@@ -97,15 +96,7 @@ def get_obj_from_dirty_text(full_object: str):
|
||||
ret = obj
|
||||
if ret is not None:
|
||||
if i + 1 < len(lines) - 1:
|
||||
print('WARNING: unparsable data...', file=sys.stderr)
|
||||
lines = lines[i+1:]
|
||||
if not lines[0]:
|
||||
lines = lines[1:]
|
||||
nret = get_obj_from_dirty_text("\n".join(lines))
|
||||
if not nret:
|
||||
nret = get_obj_from_dirty_text("\n".join(lines[1:]))
|
||||
if nret:
|
||||
ret.update(nret)
|
||||
print('Ignoring this data (below the parsed object): ' + "\n".join(lines[i+1:]), file=sys.stderr)
|
||||
return ret
|
||||
except Exception as e:
|
||||
print('Exception: ' + str(e), file=sys.stderr)
|
||||
@@ -122,7 +113,7 @@ def get_type(arg_type: str, full_line: str):
|
||||
arg_type = arg_type.lower()
|
||||
if 'array' in arg_type:
|
||||
return 'array', required, None
|
||||
if 'numeric' in arg_type or 'number' in arg_type:
|
||||
if 'numeric' in arg_type:
|
||||
return 'number', required, None
|
||||
if 'bool' in arg_type:
|
||||
return 'boolean', required, None
|
||||
@@ -132,11 +123,6 @@ def get_type(arg_type: str, full_line: str):
|
||||
properties = get_obj_from_dirty_text(full_line) if full_line is not None else None
|
||||
return 'object', required, properties
|
||||
|
||||
if arg_type.startswith('optional'):
|
||||
return 'optional', required, None
|
||||
if arg_type.startswith('json'):
|
||||
return 'json', required, None
|
||||
|
||||
print('Unable to derive type from: ' + arg_type, file=sys.stderr)
|
||||
return None, False, None
|
||||
|
||||
@@ -288,4 +274,4 @@ def write_api():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
write_api()
|
||||
write_api()
|
||||
@@ -13,22 +13,17 @@ def get_type(arg_type, full_line):
|
||||
if arg_type is None:
|
||||
return 'string'
|
||||
|
||||
arg_type = arg_type.lower().split(',')[0].strip()
|
||||
arg_type = arg_type.lower()
|
||||
if 'numeric' in arg_type:
|
||||
return 'number'
|
||||
if 'bool' in arg_type:
|
||||
return 'boolean'
|
||||
if 'array' in arg_type:
|
||||
return 'array'
|
||||
if 'string' in arg_type:
|
||||
return 'string'
|
||||
if 'object' in arg_type:
|
||||
return 'object'
|
||||
|
||||
supported_types = ['number', 'string', 'object', 'array', 'optional']
|
||||
if arg_type in supported_types:
|
||||
return arg_type
|
||||
|
||||
print("get_type: WARNING", arg_type, "is not supported type", file=sys.stderr)
|
||||
return arg_type
|
||||
raise Exception('Not implemented: ' + arg_type)
|
||||
|
||||
|
||||
def parse_params(args):
|
||||
@@ -39,7 +34,7 @@ def parse_params(args):
|
||||
continue
|
||||
arg_parsed = re_argline.fullmatch(line)
|
||||
if arg_parsed is None:
|
||||
continue
|
||||
raise Exception("Unparsable argument: " + line)
|
||||
arg_name, arg_type, arg_desc = arg_parsed.group('name', 'type', 'desc')
|
||||
if not arg_type:
|
||||
raise Exception('Not implemented: ' + arg_type)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+472
-1583
File diff suppressed because it is too large.
Load diff
@@ -36,13 +36,13 @@ if [ -z "${CODESIGN_ALLOCATE}" ]; then
|
||||
fi
|
||||
|
||||
find ${TEMPDIR} -name "*.sign" | while read i; do
|
||||
SIZE=$(stat -c %s "${i}")
|
||||
TARGET_FILE="$(echo "${i}" | sed 's/\.sign$//')"
|
||||
SIZE=`stat -c %s "${i}"`
|
||||
TARGET_FILE="`echo "${i}" | sed 's/\.sign$//'`"
|
||||
|
||||
echo "Allocating space for the signature of size ${SIZE} in ${TARGET_FILE}"
|
||||
${CODESIGN_ALLOCATE} -i "${TARGET_FILE}" -a ${ARCH} ${SIZE} -o "${i}.tmp"
|
||||
|
||||
OFFSET=$(${PAGESTUFF} "${i}.tmp" -p | tail -2 | grep offset | sed 's/[^0-9]*//g')
|
||||
OFFSET=`${PAGESTUFF} "${i}.tmp" -p | tail -2 | grep offset | sed 's/[^0-9]*//g'`
|
||||
if [ -z ${QUIET} ]; then
|
||||
echo "Attaching signature at offset ${OFFSET}"
|
||||
fi
|
||||
|
||||
@@ -27,19 +27,19 @@ ${CODESIGN} -f --file-list ${TEMPLIST} "$@" "${BUNDLE}"
|
||||
|
||||
grep -v CodeResources < "${TEMPLIST}" | while read i; do
|
||||
TARGETFILE="${BUNDLE}/`echo "${i}" | sed "s|.*${BUNDLE}/||"`"
|
||||
SIZE=$(pagestuff "$i" -p | tail -2 | grep size | sed 's/[^0-9]*//g')
|
||||
OFFSET=$(pagestuff "$i" -p | tail -2 | grep offset | sed 's/[^0-9]*//g')
|
||||
SIZE=`pagestuff "$i" -p | tail -2 | grep size | sed 's/[^0-9]*//g'`
|
||||
OFFSET=`pagestuff "$i" -p | tail -2 | grep offset | sed 's/[^0-9]*//g'`
|
||||
SIGNFILE="${TEMPDIR}/${OUTROOT}/${TARGETFILE}.sign"
|
||||
DIRNAME="$(dirname "${SIGNFILE}")"
|
||||
DIRNAME="`dirname "${SIGNFILE}"`"
|
||||
mkdir -p "${DIRNAME}"
|
||||
echo "Adding detached signature for: ${TARGETFILE}. Size: ${SIZE}. Offset: ${OFFSET}"
|
||||
dd if="$i" of="${SIGNFILE}" bs=1 skip=${OFFSET} count=${SIZE} 2>/dev/null
|
||||
done
|
||||
|
||||
grep CodeResources < "${TEMPLIST}" | while read i; do
|
||||
TARGETFILE="${BUNDLE}/$(echo "${i}" | sed "s|.*${BUNDLE}/||")"
|
||||
TARGETFILE="${BUNDLE}/`echo "${i}" | sed "s|.*${BUNDLE}/||"`"
|
||||
RESOURCE="${TEMPDIR}/${OUTROOT}/${TARGETFILE}"
|
||||
DIRNAME="$(dirname "${RESOURCE}")"
|
||||
DIRNAME="`dirname "${RESOURCE}"`"
|
||||
mkdir -p "${DIRNAME}"
|
||||
echo "Adding resource for: \"${TARGETFILE}\""
|
||||
cp "${i}" "${RESOURCE}"
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
## Stratum Server Instructions
|
||||
In simple terms, the stratum protocol is a protocol to distribute crypto mining work to multiple miners. Mining pools typically run a stratum endpoint that the various miners communicate with.
|
||||
Please refer to other web sources for more information about mining pools or the stratum protocol.
|
||||
|
||||
When mining LBC, you can solo mine directly to an instance of a full node (using the node's wallet). Or you can mine as part of a pool.
|
||||
You can host your own pool or use one of the many hosted LBC pools. See https://miningpoolstats.stream/lbry
|
||||
|
||||
This document refers to Yiimp, a derivative of Yaamp, as found here: https://github.com/tpruvot/yiimp.git .
|
||||
Please refer to the instructions there as well. Yiimp has supported LBRY mining for several years.
|
||||
|
||||
Yiimp consists of two pieces: the web GUI for pool management (written in PHP) and the Stratum server (written in C++). The two communicate via polling a MySQL database (or MariaDB).
|
||||
The web GUI and configuration of the pooling rewards, fees, etc. are out of scope here.
|
||||
|
||||
To help you with running Yiimp, we have created two docker images: one for the DB and one for the Yiimp Stratum Server. (See the subfolders.)
|
||||
Use of the Docker images is optional; you can refer to other Yiimp and MySQL documentation for running it without Docker.
|
||||
If you are using your own database instance, you will need to import the Yiimp SQL files to establish the yaamp database.
|
||||
See https://github.com/tpruvot/yiimp/tree/next/sql .
|
||||
|
||||
### Sample Usage Steps:
|
||||
|
||||
#### 1. Run the full lbrycrd node:
|
||||
```
|
||||
./lbrycrdd -testnet -rpcuser=ruser -rpcpassword=rpswd -deprecatedrpc=validateaddress -deprecatedrpc=accounts -daemon
|
||||
```
|
||||
The included deprecated RPCs are required for compatibility with Yiimp.
|
||||
It will need to be caught up to the current block before it is ready.
|
||||
Remove `-testnet` for the real deal.
|
||||
#### 2. Run and initialize the datatabase:
|
||||
```
|
||||
docker run -d -e MYSQL_ROOT_PASSWORD=patofpaq -e MYSQL_DATABASE=yaamp --network host --name db lbry/yiimp_db
|
||||
|
||||
docker exec -it db mysql -uroot -ppatofpaq
|
||||
use yaamp;
|
||||
delete from coins;
|
||||
insert into coins(name, symbol, symbol2, algo, enable, auto_ready, rpcuser, rpcpasswd, rpchost, rpcport, rpccurl, rpcencoding, hasgetinfo, hassubmitblock, usememorypool, usesegwit, auxpow)
|
||||
values('Local LBRY Instance', 'LBC', 'LBC', 'lbry', 1, 1, 'ruser', 'rpswd', '127.0.0.1', 19245, 1, 'utf-8', 0, 1, 0, 0, 0);
|
||||
exit
|
||||
```
|
||||
Use port 19245 for testnet, port 9245 for main. Set usesegwit to 1 after the segwit fork is enabled on December 11, 2019.
|
||||
#### 3. Run the stratum server:
|
||||
```
|
||||
docker run --network host -d lbry/yiimp_stratum
|
||||
```
|
||||
Alternatively, to get more output or see how its called directly:
|
||||
```
|
||||
docker run --network host -it lbry/yiimp_stratum bash
|
||||
cat config/lbry.conf
|
||||
./stratum config/lbry
|
||||
```
|
||||
When testing with an ASIC you may need to modify the TCP server address in said lbry.conf file to be an external IP address.
|
||||
|
||||
#### 4. Connect sgminer to it:
|
||||
```
|
||||
sgminer -k lbry -o stratum+tcp://127.0.0.1:3334/ -D -T -O mn824Su1wX7ip8WcNYzXwwWqvBvkeWGRo6:x
|
||||
```
|
||||
The username there is the account to receive payments from the pool. The password is unused. Tested with https://github.com/lbryio/sgminer-gm.
|
||||
You can use whatever miner you prefer.
|
||||
@@ -1,34 +0,0 @@
|
||||
FROM mariadb:10.1-bionic
|
||||
ARG REPOSITORY=https://github.com/tpruvot/yiimp.git
|
||||
|
||||
ENV BUILD_DEPS \
|
||||
ca-certificates \
|
||||
git
|
||||
|
||||
COPY init-db.sh /docker-entrypoint-initdb.d/
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ${BUILD_DEPS} \
|
||||
&& git clone --progress ${REPOSITORY} ~/yiimp \
|
||||
&& mkdir /tmp/sql \
|
||||
&& mv ~/yiimp/sql/2016-04-03-yaamp.sql.gz /tmp/sql/0000-00-00-initial.sql.gz \
|
||||
&& cp ~/yiimp/sql/*.sql /tmp/sql \
|
||||
&& apt-get purge -y --auto-remove ${BUILD_DEPS} \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& rm -rf ~/yiimp
|
||||
|
||||
EXPOSE 3306
|
||||
|
||||
ARG VCS_REF
|
||||
ARG BUILD_DATE
|
||||
LABEL maintainer="blockchain@lbry.com" \
|
||||
decription="yiimp_db" \
|
||||
version="1.0" \
|
||||
org.label-schema.name="yiimp_db" \
|
||||
org.label-schema.description="Use this to run a compatible MariaDB for yiimp's stratum server" \
|
||||
org.label-schema.build-date=$BUILD_DATE \
|
||||
org.label-schema.vcs-ref=$VCS_REF \
|
||||
org.label-schema.vcs-url="https://github.com/lbryio/lbrycrd" \
|
||||
org.label-schema.schema-version="1.0.0-rc1" \
|
||||
org.label-schema.vendor="LBRY" \
|
||||
org.label-schema.docker.cmd="docker build --build-arg BUILD_DATE=`date -u +"%Y-%m-%dT%H:%M:%SZ"` --build-arg VCS_REF=`git rev-parse --short HEAD` -t lbry/yiimp_db yiimp_db"
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
for f in /tmp/sql/*; do
|
||||
case "$f" in
|
||||
*.sql) echo "$0: running $f"; "${mysql[@]}" --force < "$f"; echo ;;
|
||||
*.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${mysql[@]}"; echo ;;
|
||||
*) echo "$0: ignoring $f" ;;
|
||||
esac
|
||||
echo
|
||||
done
|
||||
@@ -1,54 +0,0 @@
|
||||
FROM alpine:3.7
|
||||
ARG REPOSITORY=https://github.com/tpruvot/yiimp.git
|
||||
|
||||
ENV BUILD_DEPS \
|
||||
build-base \
|
||||
git
|
||||
|
||||
ENV RUN_DEPS \
|
||||
curl-dev \
|
||||
gmp-dev \
|
||||
mariadb-dev \
|
||||
libssh2-dev \
|
||||
curl
|
||||
|
||||
RUN apk update \
|
||||
&& apk add --no-cache ${BUILD_DEPS} \
|
||||
&& apk add --no-cache ${RUN_DEPS} \
|
||||
&& git clone --progress ${REPOSITORY} ~/yiimp \
|
||||
&& sed -i 's/ulong/uint64_t/g' ~/yiimp/stratum/algos/rainforest.c \
|
||||
&& find ~/yiimp -name '*akefile' -exec sed -i 's/-march=native//g' {} + \
|
||||
&& make -C ~/yiimp/stratum/iniparser \
|
||||
&& make -C ~/yiimp/stratum \
|
||||
&& mkdir /var/stratum /var/stratum/config \
|
||||
&& cp ~/yiimp/stratum/run.sh /var/stratum \
|
||||
&& cp ~/yiimp/stratum/config/run.sh /var/stratum/config \
|
||||
&& cp ~/yiimp/stratum/stratum /var/stratum \
|
||||
&& cp ~/yiimp/stratum/config.sample/lbry.conf /var/stratum/config \
|
||||
&& sed -i 's/yaamp.com/127.0.0.1/g' /var/stratum/config/lbry.conf \
|
||||
&& sed -i 's/yaampdb/127.0.0.1/g' /var/stratum/config/lbry.conf \
|
||||
&& rm -rf ~/yiimp \
|
||||
&& apk del ${BUILD_DEPS} \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
RUN apk add --no-cache bash
|
||||
|
||||
ARG VCS_REF
|
||||
ARG BUILD_DATE
|
||||
LABEL maintainer="blockchain@lbry.com" \
|
||||
decription="yiimp_stratum" \
|
||||
version="1.0" \
|
||||
org.label-schema.name="yiimp_stratum" \
|
||||
org.label-schema.description="Use this to run yiimp's stratum server in lbry mode" \
|
||||
org.label-schema.build-date=$BUILD_DATE \
|
||||
org.label-schema.vcs-ref=$VCS_REF \
|
||||
org.label-schema.vcs-url="https://github.com/lbryio/lbrycrd" \
|
||||
org.label-schema.schema-version="1.0.0-rc1" \
|
||||
org.label-schema.vendor="LBRY" \
|
||||
org.label-schema.docker.cmd="docker build --build-arg BUILD_DATE=`date -u +"%Y-%m-%dT%H:%M:%SZ"` --build-arg VCS_REF=`git rev-parse --short HEAD` -t lbry/yiimp_stratum yiimp_stratum"
|
||||
|
||||
WORKDIR /var/stratum
|
||||
|
||||
CMD ["./stratum", "config/lbry"]
|
||||
|
||||
EXPOSE 3334
|
||||
@@ -23,7 +23,7 @@ TIMESERVER=http://timestamp.comodoca.com
|
||||
CERTFILE="win-codesign.cert"
|
||||
|
||||
mkdir -p "${OUTSUBDIR}"
|
||||
basename -a $(ls -1 "${SRCDIR}"/*-unsigned.exe) | while read UNSIGNED; do
|
||||
basename -a `ls -1 "${SRCDIR}"/*-unsigned.exe` | while read UNSIGNED; do
|
||||
echo Signing "${UNSIGNED}"
|
||||
"${OSSLSIGNCODE}" sign -certs "${CERTFILE}" -t "${TIMESERVER}" -in "${SRCDIR}/${UNSIGNED}" -out "${WORKDIR}/${UNSIGNED}" "$@"
|
||||
"${OSSLSIGNCODE}" extract-signature -pem -in "${WORKDIR}/${UNSIGNED}" -out "${OUTSUBDIR}/${UNSIGNED}.pem" && rm "${WORKDIR}/${UNSIGNED}"
|
||||
|
||||
+1
-1
@@ -131,7 +131,7 @@ $(host_prefix)/share/config.site : config.site.in $(host_prefix)/.stamp_$(final_
|
||||
-e 's|@build_os@|$(build_os)|' \
|
||||
-e 's|@host_os@|$(host_os)|' \
|
||||
-e 's|@CFLAGS@|$(strip $(host_CFLAGS) $(host_$(release_type)_CFLAGS))|' \
|
||||
-e 's|@CXXFLAGS@|$(strip -pipe $(host_$(release_type)_CXXFLAGS))|' \
|
||||
-e 's|@CXXFLAGS@|$(strip $(host_CXXFLAGS) $(host_$(release_type)_CXXFLAGS))|' \
|
||||
-e 's|@CPPFLAGS@|$(strip $(host_CPPFLAGS) $(host_$(release_type)_CPPFLAGS))|' \
|
||||
-e 's|@LDFLAGS@|$(strip $(host_LDFLAGS) $(host_$(release_type)_LDFLAGS))|' \
|
||||
-e 's|@allow_host_packages@|$(ALLOW_HOST_PACKAGES)|' \
|
||||
|
||||
@@ -7,12 +7,12 @@ darwin_CC=clang -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) -isysroo
|
||||
darwin_CXX=clang++ -target $(host) -mmacosx-version-min=$(OSX_MIN_VERSION) -isysroot $(OSX_SDK) -mlinker-version=$(LD64_VERSION) -stdlib=libc++ -B $(host_prefix)/native/bin
|
||||
|
||||
darwin_CFLAGS=-pipe
|
||||
darwin_CXXFLAGS=$(darwin_CFLAGS) -std=c++11
|
||||
darwin_CXXFLAGS=$(darwin_CFLAGS)
|
||||
|
||||
darwin_release_CFLAGS=-O2 -g
|
||||
darwin_release_CFLAGS=-O2
|
||||
darwin_release_CXXFLAGS=$(darwin_release_CFLAGS)
|
||||
|
||||
darwin_debug_CFLAGS=-Og -g
|
||||
darwin_debug_CXXFLAGS=-O0 -g
|
||||
darwin_debug_CFLAGS=-Og
|
||||
darwin_debug_CXXFLAGS=$(darwin_debug_CFLAGS)
|
||||
|
||||
darwin_native_toolchain=native_cctools
|
||||
darwin_native_toolchain=native_cctools
|
||||
@@ -1,11 +1,11 @@
|
||||
linux_CFLAGS=-pipe
|
||||
linux_CXXFLAGS=$(linux_CFLAGS) -std=c++11
|
||||
linux_CXXFLAGS=$(linux_CFLAGS)
|
||||
|
||||
linux_release_CFLAGS=-O2 -g
|
||||
linux_release_CFLAGS=-O2
|
||||
linux_release_CXXFLAGS=$(linux_release_CFLAGS)
|
||||
|
||||
linux_debug_CFLAGS=-O1 -g
|
||||
linux_debug_CXXFLAGS=-O0 -g
|
||||
linux_debug_CFLAGS=-Og
|
||||
linux_debug_CXXFLAGS=$(linux_debug_CFLAGS)
|
||||
|
||||
linux_debug_CPPFLAGS=-D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
mingw32_CFLAGS=-pipe
|
||||
mingw32_CXXFLAGS=$(mingw32_CFLAGS) -std=c++11
|
||||
mingw32_CXXFLAGS=$(mingw32_CFLAGS)
|
||||
|
||||
mingw32_release_CFLAGS=-O2 -g
|
||||
mingw32_release_CFLAGS=-O2
|
||||
mingw32_release_CXXFLAGS=$(mingw32_release_CFLAGS)
|
||||
|
||||
mingw32_debug_CFLAGS=-O1 -g
|
||||
mingw32_debug_CXXFLAGS=-O0 -g
|
||||
mingw32_debug_CFLAGS=-O1
|
||||
mingw32_debug_CXXFLAGS=$(mingw32_debug_CFLAGS)
|
||||
|
||||
mingw32_debug_CPPFLAGS=-D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC
|
||||
@@ -1,6 +1,6 @@
|
||||
package=bdb
|
||||
$(package)_version=4.8.30
|
||||
$(package)_download_path=https://download.oracle.com/berkeley-db
|
||||
$(package)_download_path=http://download.oracle.com/berkeley-db
|
||||
$(package)_file_name=db-$($(package)_version).NC.tar.gz
|
||||
$(package)_sha256_hash=12edc0df75bf9abd7f82f821795bcee50f42cb2e5f76a6a281b85732798364ef
|
||||
$(package)_build_subdir=build_unix
|
||||
@@ -9,7 +9,7 @@ define $(package)_set_vars
|
||||
$(package)_config_opts=--disable-shared --enable-cxx --disable-replication
|
||||
$(package)_config_opts_mingw32=--enable-mingw
|
||||
$(package)_config_opts_linux=--with-pic
|
||||
$(package)_cppflags_mingw32=-DUNICODE -D_UNICODE
|
||||
$(package)_cxxflags=-std=c++11
|
||||
endef
|
||||
|
||||
define $(package)_preprocess_cmds
|
||||
|
||||
@@ -15,6 +15,7 @@ define $(package)_set_vars
|
||||
$(package)_archiver_darwin=$($(package)_libtool)
|
||||
$(package)_cflags_linux=-fPIC
|
||||
$(package)_cppflags_linux=-fPIC
|
||||
$(package)_cxxflags=-std=c++11
|
||||
endef
|
||||
|
||||
define $(package)_preprocess_cmds
|
||||
@@ -30,8 +31,6 @@ define $(package)_config_cmds
|
||||
PKG_CONFIG_SYSROOT_DIR=/ \
|
||||
PKG_CONFIG_LIBDIR=$(host_prefix)/lib/pkgconfig \
|
||||
PKG_CONFIG_PATH=$(host_prefix)/share/pkgconfig \
|
||||
sed -i.old 's/^GEN_DEPS.c=.*/& $($(package)_cflags)/' config/mh-mingw* && \
|
||||
sed -i.old 's/^GEN_DEPS.cc=.*/& $($(package)_cxxflags)/' config/mh-mingw* && \
|
||||
$($(package)_autoconf)
|
||||
endef
|
||||
|
||||
|
||||
@@ -27,5 +27,4 @@ define $(package)_stage_cmds
|
||||
endef
|
||||
|
||||
define $(package)_postprocess_cmds
|
||||
rm lib/*.la
|
||||
endef
|
||||
@@ -4,6 +4,7 @@ $(package)_download_path=$(native_$(package)_download_path)
|
||||
$(package)_file_name=$(native_$(package)_file_name)
|
||||
$(package)_sha256_hash=$(native_$(package)_sha256_hash)
|
||||
$(package)_dependencies=native_$(package)
|
||||
$(package)_cxxflags=-std=c++11
|
||||
|
||||
define $(package)_set_vars
|
||||
$(package)_config_opts=--disable-shared --with-protoc=$(build_prefix)/bin/protoc
|
||||
|
||||
@@ -2,9 +2,6 @@ PACKAGE=qt
|
||||
$(package)_version=5.9.6
|
||||
$(package)_download_path=https://download.qt.io/official_releases/qt/5.9/$($(package)_version)/submodules
|
||||
$(package)_suffix=opensource-src-$($(package)_version).tar.xz
|
||||
#$(package)_version=5.12.3
|
||||
#$(package)_download_path=http://download.qt.io/official_releases/qt/5.12/$($(package)_version)/submodules
|
||||
#$(package)_suffix=opensource-src-$($(package)_version).tar.gz
|
||||
$(package)_file_name=qtbase-$($(package)_suffix)
|
||||
$(package)_sha256_hash=eed620cb268b199bd83b3fc6a471c51d51e1dc2dbb5374fc97a0cc75facbe36f
|
||||
$(package)_dependencies=openssl zlib
|
||||
|
||||
@@ -6,10 +6,9 @@ $(package)_sha256_hash=bcbabe1e2c7d0eec4ed612e10b94b112dd5f06fcefa994a0c79a45d83
|
||||
$(package)_patches=0001-fix-build-with-older-mingw64.patch 0002-disable-pthread_set_name_np.patch
|
||||
|
||||
define $(package)_set_vars
|
||||
$(package)_config_opts=--without-docs --disable-shared --without-libsodium --disable-curve --disable-curve-keygen --disable-perf --disable-Werror --disable-drafts
|
||||
$(package)_config_opts += --without-libsodium --without-libgssapi_krb5 --without-pgm --without-norm --without-vmci
|
||||
$(package)_config_opts += --disable-libunwind --disable-radix-tree --without-gcov
|
||||
$(package)_config_opts=--without-docs --disable-shared --without-libsodium --disable-curve --disable-curve-keygen --disable-perf --disable-Werror
|
||||
$(package)_config_opts_linux=--with-pic
|
||||
$(package)_cxxflags=-std=c++11
|
||||
endef
|
||||
|
||||
define $(package)_preprocess_cmds
|
||||
@@ -32,5 +31,5 @@ endef
|
||||
|
||||
define $(package)_postprocess_cmds
|
||||
sed -i.old "s/ -lstdc++//" lib/pkgconfig/libzmq.pc && \
|
||||
rm -rf bin share lib/*.la
|
||||
rm -rf bin share
|
||||
endef
|
||||
+16
-16
@@ -1,6 +1,21 @@
|
||||
FROM ubuntu:16.04
|
||||
|
||||
ARG VCS_REF
|
||||
ARG BUILD_DATE
|
||||
|
||||
ENV LANG C.UTF-8
|
||||
|
||||
LABEL maintainer="Brannon King" \
|
||||
decription="build_lbrycrd" \
|
||||
version="1.0" \
|
||||
org.label-schema.name="build_lbrycrd" \
|
||||
org.label-schema.description="Use this to generate a reproducible build of LBRYcrd" \
|
||||
org.label-schema.build-date=$BUILD_DATE \
|
||||
org.label-schema.vcs-ref=$VCS_REF \
|
||||
org.label-schema.vcs-url="https://github.com/lbryio/lbrycrd" \
|
||||
org.label-schema.schema-version="1.0.0-rc1" \
|
||||
org.label-schema.docker.cmd="docker build --build-arg BUILD_DATE=`date -u +"%Y-%m-%dT%H:%M:%SZ"` --build-arg VCS_REF=`git rev-parse --short HEAD` -t build_lbrycrd packaging"
|
||||
|
||||
RUN set -xe; \
|
||||
apt-get update; \
|
||||
apt-get install --no-install-recommends -y build-essential libtool autotools-dev automake pkg-config git wget apt-utils \
|
||||
@@ -21,22 +36,7 @@ RUN update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang-cpp-8
|
||||
update-alternatives --set x86_64-w64-mingw32-g++ /usr/bin/x86_64-w64-mingw32-g++-posix; \
|
||||
update-alternatives --set i686-w64-mingw32-g++ /usr/bin/i686-w64-mingw32-g++-posix; \
|
||||
/usr/sbin/update-ccache-symlinks; \
|
||||
cd /usr/include/c++ && ln -s /usr/lib/llvm-8/include/c++/v1; \
|
||||
cd /usr/lib/llvm-8/lib && ln -s libc++abi.so.1 libc++abi.so;
|
||||
|
||||
ARG VCS_REF
|
||||
ARG BUILD_DATE
|
||||
LABEL maintainer="blockchain@lbry.com" \
|
||||
decription="build_lbrycrd" \
|
||||
version="1.1" \
|
||||
org.label-schema.name="build_lbrycrd" \
|
||||
org.label-schema.description="Use this to generate a reproducible build of LBRYcrd" \
|
||||
org.label-schema.build-date=$BUILD_DATE \
|
||||
org.label-schema.vcs-ref=$VCS_REF \
|
||||
org.label-schema.vcs-url="https://github.com/lbryio/lbrycrd" \
|
||||
org.label-schema.schema-version="1.0.0-rc1" \
|
||||
org.label-schema.vendor="LBRY" \
|
||||
org.label-schema.docker.cmd="docker build --build-arg BUILD_DATE=`date -u +"%Y-%m-%dT%H:%M:%SZ"` --build-arg VCS_REF=`git rev-parse --short HEAD` -t lbry/build_lbrycrd packaging"
|
||||
cd /usr/include/c++ && ln -s /usr/lib/llvm-8/include/c++/v1;
|
||||
|
||||
ENV PATH "/usr/lib/ccache:$PATH"
|
||||
WORKDIR /home
|
||||
|
||||
@@ -30,13 +30,13 @@ if which ccache >/dev/null; then
|
||||
fi
|
||||
|
||||
pushd depends
|
||||
make -j$(getconf _NPROCESSORS_ONLN) HOST=x86_64-apple-darwin14 NO_QT=1 V=1
|
||||
make -j`getconf _NPROCESSORS_ONLN` HOST=x86_64-apple-darwin14 NO_QT=1 V=1
|
||||
popd
|
||||
|
||||
./autogen.sh
|
||||
DEPS_DIR=$(pwd)/depends/x86_64-apple-darwin14
|
||||
DEPS_DIR=`pwd`/depends/x86_64-apple-darwin14
|
||||
CONFIG_SITE=${DEPS_DIR}/share/config.site ./configure --enable-reduce-exports --without-gui --with-icu="${DEPS_DIR}" --enable-static --disable-shared
|
||||
make -j$(getconf _NPROCESSORS_ONLN)
|
||||
make -j`getconf _NPROCESSORS_ONLN`
|
||||
${DEPS_DIR}/native/bin/x86_64-apple-darwin14-strip src/lbrycrdd src/lbrycrd-cli src/lbrycrd-tx
|
||||
|
||||
if which ccache >/dev/null; then
|
||||
|
||||
@@ -16,17 +16,14 @@ if which ccache >/dev/null; then
|
||||
ccache -ps
|
||||
fi
|
||||
|
||||
export CXXFLAGS="${CXXFLAGS:--frecord-gcc-switches}"
|
||||
echo "CXXFLAGS set to $CXXFLAGS"
|
||||
|
||||
cd depends
|
||||
make -j$(getconf _NPROCESSORS_ONLN) HOST=x86_64-pc-linux-gnu NO_QT=1 V=1
|
||||
make -j`getconf _NPROCESSORS_ONLN` HOST=x86_64-pc-linux-gnu NO_QT=1 V=1
|
||||
cd ..
|
||||
|
||||
./autogen.sh
|
||||
DEPS_DIR=$(pwd)/depends/x86_64-pc-linux-gnu
|
||||
DEPS_DIR=`pwd`/depends/x86_64-pc-linux-gnu
|
||||
CONFIG_SITE=${DEPS_DIR}/share/config.site ./configure --enable-static --disable-shared --with-pic --without-gui
|
||||
make -j$(getconf _NPROCESSORS_ONLN)
|
||||
make -j`getconf _NPROCESSORS_ONLN`
|
||||
strip src/lbrycrdd src/lbrycrd-cli src/lbrycrd-tx
|
||||
|
||||
if which ccache >/dev/null; then
|
||||
@@ -34,4 +31,4 @@ if which ccache >/dev/null; then
|
||||
ccache -s
|
||||
fi
|
||||
|
||||
echo "Linux 64bit build is complete"
|
||||
echo "Linux 64bit build is complete"
|
||||
@@ -21,13 +21,13 @@ if which ccache >/dev/null; then
|
||||
fi
|
||||
|
||||
pushd depends
|
||||
make -j$(getconf _NPROCESSORS_ONLN) HOST=i686-w64-mingw32 NO_QT=1 V=1
|
||||
make -j`getconf _NPROCESSORS_ONLN` HOST=i686-w64-mingw32 NO_QT=1 V=1
|
||||
popd
|
||||
|
||||
./autogen.sh
|
||||
DEPS_DIR=$(pwd)/depends/i686-w64-mingw32
|
||||
DEPS_DIR=`pwd`/depends/i686-w64-mingw32
|
||||
CONFIG_SITE=${DEPS_DIR}/share/config.site ./configure --prefix=/ --without-gui --with-icu="$DEPS_DIR" --enable-static --disable-shared
|
||||
make -j$(getconf _NPROCESSORS_ONLN)
|
||||
make -j`getconf _NPROCESSORS_ONLN`
|
||||
i686-w64-mingw32-strip src/lbrycrdd.exe src/lbrycrd-cli.exe src/lbrycrd-tx.exe
|
||||
|
||||
if which ccache >/dev/null; then
|
||||
|
||||
@@ -20,13 +20,13 @@ if which ccache >/dev/null; then
|
||||
fi
|
||||
|
||||
pushd depends
|
||||
make -j$(getconf _NPROCESSORS_ONLN) HOST=x86_64-w64-mingw32 NO_QT=1 V=1
|
||||
make -j`getconf _NPROCESSORS_ONLN` HOST=x86_64-w64-mingw32 NO_QT=1 V=1
|
||||
popd
|
||||
|
||||
./autogen.sh
|
||||
DEPS_DIR=$(pwd)/depends/x86_64-w64-mingw32
|
||||
DEPS_DIR=`pwd`/depends/x86_64-w64-mingw32
|
||||
CONFIG_SITE=${DEPS_DIR}/share/config.site ./configure --prefix=/ --without-gui --with-icu="$DEPS_DIR" --enable-static --disable-shared
|
||||
make -j$(getconf _NPROCESSORS_ONLN)
|
||||
make -j`getconf _NPROCESSORS_ONLN`
|
||||
x86_64-w64-mingw32-strip src/lbrycrdd.exe src/lbrycrd-cli.exe src/lbrycrd-tx.exe
|
||||
|
||||
if which ccache >/dev/null; then
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
FROM ubuntu:18.04 as prep
|
||||
LABEL MAINTAINER="leopere [at] nixc [dot] us"
|
||||
## TODO: Implement version pinning. `apt-get install curl=<version>`
|
||||
RUN apt-get update && \
|
||||
apt-get -y install unzip curl build-essential && \
|
||||
apt-get autoclean -y && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /
|
||||
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
|
||||
COPY ./stuff/start.sh start
|
||||
COPY ./stuff/healthcheck.sh healthcheck
|
||||
COPY ./stuff/advance_blocks.sh advance
|
||||
COPY ./stuff/fix-permissions.c fix-permissions.c
|
||||
ARG release_url
|
||||
# require that release_url is set
|
||||
RUN test -n "$release_url"
|
||||
RUN curl --progress-bar -L -o ./lbrycrd-linux.zip "$release_url" && \
|
||||
unzip ./lbrycrd-linux.zip && \
|
||||
gcc fix-permissions.c -o fix-permissions && \
|
||||
chmod +x ./lbrycrdd ./lbrycrd-cli ./lbrycrd-tx ./start ./healthcheck ./fix-permissions ./advance
|
||||
|
||||
FROM ubuntu:18.04 as app
|
||||
COPY --from=prep /lbrycrdd /lbrycrd-cli /lbrycrd-tx /start /healthcheck /fix-permissions /advance /usr/bin/
|
||||
RUN addgroup --gid 1000 lbrycrd && \
|
||||
adduser lbrycrd --uid 1000 --gid 1000 --gecos GECOS --shell /bin/bash --disabled-password --home /data && \
|
||||
mkdir /etc/lbry && \
|
||||
chown lbrycrd /etc/lbry && \
|
||||
chmod a+s /usr/bin/fix-permissions
|
||||
RUN apt-get update && apt-get -y install wget && apt-get autoclean -y && rm -rf /var/lib/apt/lists/*
|
||||
VOLUME ["/data"]
|
||||
WORKDIR /data
|
||||
HEALTHCHECK CMD /usr/bin/healthcheck
|
||||
EXPOSE 9246 9245 11337 29245
|
||||
|
||||
USER lbrycrd
|
||||
CMD ["start"]
|
||||
@@ -1,45 +0,0 @@
|
||||
# lbrycrd Docker image
|
||||
`
|
||||
|
||||
## Configuration
|
||||
|
||||
The lbrycrd container comes with a default configuration you can use for
|
||||
production. Extra configuration is optional.
|
||||
|
||||
The container includes a `start` script that offers a flexible configuration
|
||||
style. It allows you to mount your own `lbrycrd.conf` file, or use environment
|
||||
variables, or a mix of both.
|
||||
|
||||
### Environment variables
|
||||
|
||||
The environment variables override the values in the mounted config file. If no
|
||||
mounted config file exists, these variables are used to create a fresh config.
|
||||
|
||||
* `PORT` - The main lbrycrd port
|
||||
* `RPC_USER` - The rpc user
|
||||
* `RPC_PASSWORD` - The rpc user's password
|
||||
* `RPC_ALLOW_IP` - the subnet that is allowed rpc access
|
||||
* `RPC_PORT` - The port to bind the rpc service to
|
||||
* `RPC_BIND` - The ip address to bind the rpc service to
|
||||
|
||||
|
||||
### Example run commands
|
||||
|
||||
Running the default configuration:
|
||||
|
||||
```
|
||||
docker run --rm -it -e RUN_MODE=default -e SNAPSHOT_URL="https://lbry.com/snapshot/blockchain" lbry/lbrycrd:latest-release
|
||||
```
|
||||
|
||||
Running with RPC password changed:
|
||||
|
||||
```
|
||||
docker run --rm -it -e RUN_MODE=default -e RPC_PASSWORD=hunter2 lbry/lbrycrd:latest-release
|
||||
```
|
||||
|
||||
Running with a config file but with the RPC password still overridden:
|
||||
|
||||
```
|
||||
docker run --rm -it -v /path/to/lbrycrd.conf:/etc/lbry/lbrycrd.conf -e RUN_MODE=default -e RPC_PASSWORD=hunter2 lbry/lbrycrd:latest-release
|
||||
```
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
version: '3.4'
|
||||
|
||||
networks:
|
||||
lbry-network:
|
||||
external: true
|
||||
|
||||
services:
|
||||
#############
|
||||
## Lbrycrd ##
|
||||
#############
|
||||
lbrycrd:
|
||||
build: .
|
||||
restart: always
|
||||
networks:
|
||||
lbry-network:
|
||||
ipv4_address: 10.6.1.2
|
||||
environment:
|
||||
RUN_MODE: default
|
||||
env_file:
|
||||
- env
|
||||
expose:
|
||||
- 9245
|
||||
- 9246
|
||||
## host volumes for persistent data such as wallet private keys.
|
||||
volumes:
|
||||
- "../persist/data:/data"
|
||||
@@ -1,28 +0,0 @@
|
||||
version: '3.4'
|
||||
|
||||
networks:
|
||||
lbry-network:
|
||||
external: true
|
||||
|
||||
services:
|
||||
#############
|
||||
## Lbrycrd ##
|
||||
#############
|
||||
lbrycrd:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: always
|
||||
ports:
|
||||
- "11336:29246"
|
||||
- "11337:29245"
|
||||
## host volumes for persistent data such as wallet private keys.
|
||||
volumes:
|
||||
- "../persist/data:/data"
|
||||
networks:
|
||||
lbry-network:
|
||||
ipv4_address: 10.6.1.2
|
||||
environment:
|
||||
- RUN_MODE=regtest
|
||||
- PORT=29245
|
||||
- AUTO_ADVANCE=1
|
||||
@@ -1,17 +0,0 @@
|
||||
version: '3.4'
|
||||
|
||||
services:
|
||||
#############
|
||||
## Lbrycrd ##
|
||||
#############
|
||||
lbrycrd:
|
||||
image: lbry/lbrycrd:latest-release
|
||||
restart: always
|
||||
ports:
|
||||
- "11336:9246"
|
||||
- "11337:11337"
|
||||
## host volumes for persistent data such as wallet private keys.
|
||||
volumes:
|
||||
- "../persist/data:/data"
|
||||
environment:
|
||||
- RUN_MODE=testnet
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
hash docker 2>/dev/null || { echo >&2 'Make sure Docker is installed'; exit 1; }
|
||||
|
||||
set +eo pipefail
|
||||
docker version | grep -q Server
|
||||
ret=$?
|
||||
set -eo pipefail
|
||||
|
||||
if [ $ret -ne 0 ]; then
|
||||
echo "Cannot connect to Docker server. Is it running? Do you have the right user permissions?"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "This will build the docker image using the latest lbrycrd release and push that image to Docker Hub"
|
||||
echo ""
|
||||
|
||||
echo "What Docker tag should I use? It's the part that goes here: lbry/lbrycrd:TAG"
|
||||
|
||||
read -p "Docker tag: " docker_tag
|
||||
if [ -z "$docker_tag" ]; then
|
||||
echo "Docker tag cannot be empty"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
|
||||
release_url=$(curl -s https://api.github.com/repos/lbryio/lbrycrd/releases | grep -F 'lbrycrd-linux' | grep download | head -n 1 | cut -d'"' -f4)
|
||||
|
||||
docker build --build-arg "release_url=$release_url" --tag "lbry/lbrycrd:${docker_tag}" -f Dockerfile "$DIR"
|
||||
docker push "lbry/lbrycrd:${docker_tag}"
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
while sleep 2; do
|
||||
lbrycrd-cli -conf=/etc/lbry/lbrycrd.conf generate 1
|
||||
done
|
||||
@@ -1,12 +0,0 @@
|
||||
COMPOSE_PROJECT_NAME=lbrycrd
|
||||
|
||||
#############
|
||||
## Lbrycrd ##
|
||||
#############
|
||||
## TODO: The credentials are a formality but we should randomize these with magic.
|
||||
RPC_USER=${RPC_USER=lbryrpc}
|
||||
RPC_PASSWORD=${RPC_PASSWORD:-changeme}
|
||||
|
||||
## This should be the internal container IP from which you'll be calling the RPC for Lbrycrdd from.
|
||||
## TODO: make this more dynamic before we move to scalability
|
||||
RPC_ALLOW_IP=${RPC_ALLOW_IP:-10.6.1.3}
|
||||
@@ -1,9 +0,0 @@
|
||||
#include <unistd.h>
|
||||
int main() {
|
||||
// This program needs to run with setuid == root
|
||||
// This needs to be in a compiled language because you cannot setuid bash scripts
|
||||
setuid(0);
|
||||
execle("/bin/bash", "bash", "-c",
|
||||
"/bin/chown -R lbrycrd:lbrycrd /data && /bin/chmod -R 755 /data/",
|
||||
(char*) NULL, (char*) NULL);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
/usr/bin/lbrycrd-cli -conf=/etc/lbry/lbrycrd.conf getnetworkinfo | grep -q '"networkactive": true,'
|
||||
@@ -1,139 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CONFIG_PATH=/etc/lbry/lbrycrd.conf
|
||||
|
||||
|
||||
function override_config_option() {
|
||||
# Remove existing config line from a config file
|
||||
# and replace with environment fed value.
|
||||
# Does nothing if the variable does not exist.
|
||||
# var Name of ENV variable
|
||||
# option Name of config option
|
||||
# config Path of config file
|
||||
local var=$1 option=$2 config=$3
|
||||
if [[ -v $var ]]; then
|
||||
# Remove the existing config option:
|
||||
sed -i "/^$option\W*=/d" $config
|
||||
# Add the value from the environment:
|
||||
echo "$option=${!var}" >> $config
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
function set_config() {
|
||||
if [ -d "$CONFIG_PATH" ]; then
|
||||
echo "$CONFIG_PATH is a directory when it should be a file."
|
||||
exit 1
|
||||
elif [ -f "$CONFIG_PATH" ]; then
|
||||
echo "Merging the mounted config file with environment variables."
|
||||
local MERGED_CONFIG=/tmp/lbrycrd_merged.conf
|
||||
cp $CONFIG_PATH $MERGED_CONFIG
|
||||
echo "" >> $MERGED_CONFIG
|
||||
override_config_option PORT port $MERGED_CONFIG
|
||||
override_config_option RPC_USER rpcuser $MERGED_CONFIG
|
||||
override_config_option RPC_PASSWORD rpcpassword $MERGED_CONFIG
|
||||
override_config_option RPC_ALLOW_IP rpcallowip $MERGED_CONFIG
|
||||
override_config_option RPC_PORT rpcport $MERGED_CONFIG
|
||||
override_config_option RPC_BIND rpcbind $MERGED_CONFIG
|
||||
override_config_option TX_INDEX txindex $MERGED_CONFIG
|
||||
override_config_option MAX_TX_FEE maxtxfee $MERGED_CONFIG
|
||||
override_config_option DUST_RELAY_FEE dustrelayfee $MERGED_CONFIG
|
||||
# Make the new merged config file the new CONFIG_PATH
|
||||
# This ensures that the original file the user mounted remains unmodified
|
||||
CONFIG_PATH=$MERGED_CONFIG
|
||||
else
|
||||
echo "Creating a fresh config file from environment variables."
|
||||
cat << EOF > $CONFIG_PATH
|
||||
server=1
|
||||
printtoconsole=1
|
||||
|
||||
port=${PORT:-9246}
|
||||
rpcuser=${RPC_USER:-lbry}
|
||||
rpcpassword=${RPC_PASSWORD:-lbry}
|
||||
rpcallowip=${RPC_ALLOW_IP:-127.0.0.1}
|
||||
rpcport=${RPC_PORT:-9245}
|
||||
rpcbind=${RPC_BIND:-"0.0.0.0"}
|
||||
|
||||
txindex=${TX_INDEX:-"1"}
|
||||
maxtxfee=${MAX_TX_FEE:-"0.5"}
|
||||
dustrelayfee=${DUST_RELAY_FEE:-"0.00000001"}
|
||||
EOF
|
||||
fi
|
||||
echo "Config: "
|
||||
cat $CONFIG_PATH
|
||||
}
|
||||
|
||||
|
||||
function download_snapshot() {
|
||||
local url="${SNAPSHOT_URL:-}" #off by default. latest snapshot at https://lbry.com/snapshot/blockchain
|
||||
if [[ -n "$url" ]] && [[ ! -d ./.lbrycrd/blocks ]]; then
|
||||
echo "Downloading blockchain snapshot from $url"
|
||||
wget --no-verbose -O snapshot.tar.bz2 "$url"
|
||||
echo "Extracting snapshot..."
|
||||
mkdir -p ./.lbrycrd
|
||||
tar xvjf snapshot.tar.bz2 --directory ./.lbrycrd
|
||||
rm snapshot.tar.bz2
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
## Ensure perms are correct prior to running main binary
|
||||
/usr/bin/fix-permissions
|
||||
|
||||
|
||||
## You can optionally specify a run mode if you want to use lbry defined presets for compatibility.
|
||||
case $RUN_MODE in
|
||||
default )
|
||||
set_config
|
||||
download_snapshot
|
||||
exec lbrycrdd -conf=$CONFIG_PATH
|
||||
;;
|
||||
## If it's a first run you need to do a full index including all transactions
|
||||
## tx index creates an index of every single transaction in the block history if
|
||||
## not specified it will only create an index for transactions that are related to the wallet or have unspent outputs.
|
||||
## This is generally specific to chainquery.
|
||||
reindex )
|
||||
## Apply this RUN_MODE in the case you need to update a dataset. NOTE: you do not need to use `RUN_MODE reindex` for more than one complete run.
|
||||
set_config
|
||||
exec lbrycrdd -conf=$CONFIG_PATH -reindex
|
||||
;;
|
||||
regtest )
|
||||
## Set config params
|
||||
## TODO: Make this more automagic in the future.
|
||||
mkdir -p `dirname $CONFIG_PATH`
|
||||
echo "rpcuser=lbry" > $CONFIG_PATH
|
||||
echo "rpcpassword=lbry" >> $CONFIG_PATH
|
||||
echo "rpcport=29245" >> $CONFIG_PATH
|
||||
echo "rpcbind=0.0.0.0" >> $CONFIG_PATH
|
||||
echo "rpcallowip=0.0.0.0/0" >> $CONFIG_PATH
|
||||
echo "regtest=1" >> $CONFIG_PATH
|
||||
echo "txindex=1" >> $CONFIG_PATH
|
||||
echo "server=1" >> $CONFIG_PATH
|
||||
echo "printtoconsole=1" >> $CONFIG_PATH
|
||||
|
||||
[ "${AUTO_ADVANCE:-0}" == "1" ] && nohup advance &>/dev/null &
|
||||
|
||||
exec lbrycrdd -conf=$CONFIG_PATH $1
|
||||
;;
|
||||
testnet )
|
||||
## Set config params
|
||||
## TODO: Make this more automagic in the future.
|
||||
mkdir -p `dirname $CONFIG_PATH`
|
||||
echo "rpcuser=lbry" > $CONFIG_PATH
|
||||
echo "rpcpassword=lbry" >> $CONFIG_PATH
|
||||
echo "rpcport=29245" >> $CONFIG_PATH
|
||||
echo "rpcbind=0.0.0.0" >> $CONFIG_PATH
|
||||
echo "rpcallowip=0.0.0.0/0" >> $CONFIG_PATH
|
||||
echo "testnet=1" >> $CONFIG_PATH
|
||||
echo "txindex=1" >> $CONFIG_PATH
|
||||
echo "server=1" >> $CONFIG_PATH
|
||||
echo "printtoconsole=1" >> $CONFIG_PATH
|
||||
|
||||
#nohup advance &>/dev/null &
|
||||
exec lbrycrdd -conf=$CONFIG_PATH $1
|
||||
;;
|
||||
* )
|
||||
echo "Error, you must define a RUN_MODE environment variable."
|
||||
echo "Available options are testnet, regtest, chainquery, default, and reindex"
|
||||
;;
|
||||
esac
|
||||
+21
-25
@@ -19,18 +19,16 @@ else
|
||||
LIBUNIVALUE = $(UNIVALUE_LIBS)
|
||||
endif
|
||||
|
||||
BITCOIN_INCLUDES=-I$(builddir) $(BDB_CPPFLAGS) $(ICU_CPPFLAGS) $(BOOST_CPPFLAGS) $(CRYPTO_CFLAGS) $(ICU_CFLAGS)
|
||||
BITCOIN_INCLUDES=-I$(builddir) $(BDB_CPPFLAGS) $(ICU_CPPFLAGS) $(BOOST_CPPFLAGS) $(LEVELDB_CPPFLAGS) $(CRYPTO_CFLAGS) $(ICU_CFLAGS)
|
||||
|
||||
BITCOIN_INCLUDES += -I$(srcdir)/secp256k1/include
|
||||
BITCOIN_INCLUDES += $(UNIVALUE_CFLAGS)
|
||||
BITCOIN_INCLUDES += -I$(srcdir)/claimtrie
|
||||
|
||||
LIBBITCOIN_SERVER=libbitcoin_server.a
|
||||
LIBBITCOIN_COMMON=libbitcoin_common.a
|
||||
LIBBITCOIN_CONSENSUS=libbitcoin_consensus.a
|
||||
LIBBITCOIN_CLI=libbitcoin_cli.a
|
||||
LIBBITCOIN_UTIL=libbitcoin_util.a
|
||||
LIBCLAIMTRIE=claimtrie/libclaimtrie.a
|
||||
LIBBITCOIN_CRYPTO_BASE=crypto/libbitcoin_crypto_base.a
|
||||
LIBBITCOINQT=qt/libbitcoinqt.a
|
||||
LIBSECP256K1=secp256k1/libsecp256k1.la
|
||||
@@ -65,7 +63,6 @@ $(LIBSECP256K1): $(wildcard secp256k1/src/*.h) $(wildcard secp256k1/src/*.c) $(w
|
||||
# Make is not made aware of per-object dependencies to avoid limiting building parallelization
|
||||
# But to build the less dependent modules first, we manually select their order here:
|
||||
EXTRA_LIBRARIES += \
|
||||
$(LIBCLAIMTRIE) \
|
||||
$(LIBBITCOIN_CRYPTO) \
|
||||
$(LIBBITCOIN_UTIL) \
|
||||
$(LIBBITCOIN_COMMON) \
|
||||
@@ -106,7 +103,7 @@ BITCOIN_CORE_H = \
|
||||
checkpoints.h \
|
||||
checkqueue.h \
|
||||
claimscriptop.h \
|
||||
claimtrie_serial.h \
|
||||
claimtrie.h \
|
||||
clientversion.h \
|
||||
coins.h \
|
||||
compat.h \
|
||||
@@ -122,6 +119,8 @@ BITCOIN_CORE_H = \
|
||||
fs.h \
|
||||
httprpc.h \
|
||||
httpserver.h \
|
||||
index/base.h \
|
||||
index/txindex.h \
|
||||
indirectmap.h \
|
||||
init.h \
|
||||
interfaces/handler.h \
|
||||
@@ -131,6 +130,7 @@ BITCOIN_CORE_H = \
|
||||
key_io.h \
|
||||
keystore.h \
|
||||
lbry.h \
|
||||
dbwrapper.h \
|
||||
limitedmap.h \
|
||||
logging.h \
|
||||
memusage.h \
|
||||
@@ -154,7 +154,6 @@ BITCOIN_CORE_H = \
|
||||
reverse_iterator.h \
|
||||
reverselock.h \
|
||||
rpc/blockchain.h \
|
||||
rpc/claimrpchelp.h \
|
||||
rpc/client.h \
|
||||
rpc/mining.h \
|
||||
rpc/protocol.h \
|
||||
@@ -229,10 +228,15 @@ libbitcoin_server_a_SOURCES = \
|
||||
chain.cpp \
|
||||
checkpoints.cpp \
|
||||
claimscriptop.cpp \
|
||||
claimtrie.cpp \
|
||||
claimtrieforks.cpp \
|
||||
consensus/tx_verify.cpp \
|
||||
httprpc.cpp \
|
||||
httpserver.cpp \
|
||||
index/base.cpp \
|
||||
index/txindex.cpp \
|
||||
init.cpp \
|
||||
dbwrapper.cpp \
|
||||
lbry.cpp \
|
||||
merkleblock.cpp \
|
||||
miner.cpp \
|
||||
@@ -406,21 +410,6 @@ libbitcoin_common_a_SOURCES = \
|
||||
warnings.cpp \
|
||||
$(BITCOIN_CORE_H)
|
||||
|
||||
# claimtrie: shared between all executables.
|
||||
claimtrie_libclaimtrie_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES)
|
||||
claimtrie_libclaimtrie_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
|
||||
claimtrie_libclaimtrie_a_CFLAGS = $(PIE_FLAGS)
|
||||
claimtrie_libclaimtrie_a_SOURCES = \
|
||||
claimtrie/blob.cpp \
|
||||
claimtrie/data.cpp \
|
||||
claimtrie/forks.cpp \
|
||||
claimtrie/hashes.cpp \
|
||||
claimtrie/log.cpp \
|
||||
claimtrie/sqlite/sqlite3.c \
|
||||
claimtrie/trie.cpp \
|
||||
claimtrie/txoutpoint.cpp \
|
||||
claimtrie/uints.cpp
|
||||
|
||||
# util: shared between all executables.
|
||||
# This library *must* be included to make sure that the glibc
|
||||
# backward-compatibility objects and their sanity checks are linked.
|
||||
@@ -483,10 +472,12 @@ lbrycrdd_LDADD = \
|
||||
$(LIBBITCOIN_ZMQ) \
|
||||
$(LIBBITCOIN_CONSENSUS) \
|
||||
$(LIBBITCOIN_CRYPTO) \
|
||||
$(LIBLEVELDB) \
|
||||
$(LIBLEVELDB_SSE42) \
|
||||
$(LIBMEMENV) \
|
||||
$(LIBSECP256K1)
|
||||
|
||||
lbrycrdd_LDADD += $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(BDB_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS) $(MINIUPNPC_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) $(ZMQ_LIBS)
|
||||
lbrycrdd_LDADD += $(BOOST_LIBS) $(BDB_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS) $(MINIUPNPC_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS) $(ZMQ_LIBS)
|
||||
|
||||
# lbrycrd-cli binary #
|
||||
lbrycrd_cli_SOURCES = bitcoin-cli.cpp
|
||||
@@ -504,7 +495,7 @@ lbrycrd_cli_LDADD = \
|
||||
$(LIBBITCOIN_UTIL) \
|
||||
$(LIBBITCOIN_CRYPTO)
|
||||
|
||||
lbrycrd_cli_LDADD += $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(CRYPTO_LIBS) $(ICU_LIBS) $(EVENT_LIBS)
|
||||
lbrycrd_cli_LDADD += $(BOOST_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS) $(EVENT_LIBS)
|
||||
#
|
||||
|
||||
# bitcoin-tx binary #
|
||||
@@ -525,7 +516,7 @@ lbrycrd_tx_LDADD = \
|
||||
$(LIBBITCOIN_CRYPTO) \
|
||||
$(LIBSECP256K1)
|
||||
|
||||
lbrycrd_tx_LDADD += $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(ICU_LIBS) $(CRYPTO_LIBS)
|
||||
lbrycrd_tx_LDADD += $(BOOST_LIBS) $(ICU_LIBS) $(CRYPTO_LIBS)
|
||||
#
|
||||
|
||||
# bitcoinconsensus library #
|
||||
@@ -539,7 +530,7 @@ endif
|
||||
|
||||
libbitcoinconsensus_la_LDFLAGS = $(AM_LDFLAGS) -no-undefined $(RELDFLAGS)
|
||||
libbitcoinconsensus_la_LIBADD = $(LIBSECP256K1)
|
||||
libbitcoinconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(srcdir)/claimtrie -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL
|
||||
libbitcoinconsensus_la_CPPFLAGS = $(AM_CPPFLAGS) -I$(builddir)/obj -I$(srcdir)/secp256k1/include -DBUILD_BITCOIN_INTERNAL
|
||||
libbitcoinconsensus_la_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
|
||||
|
||||
endif
|
||||
@@ -580,6 +571,7 @@ $(top_srcdir)/$(subdir)/config/bitcoin-config.h.in: $(am__configure_deps)
|
||||
clean-local:
|
||||
-$(MAKE) -C secp256k1 clean
|
||||
-$(MAKE) -C univalue clean
|
||||
-rm -f leveldb/*/*.gcda leveldb/*/*.gcno leveldb/helpers/memenv/*.gcda leveldb/helpers/memenv/*.gcno
|
||||
-rm -f config.h
|
||||
-rm -rf test/__pycache__
|
||||
|
||||
@@ -604,6 +596,10 @@ endif
|
||||
@test -f $(PROTOC)
|
||||
$(AM_V_GEN) $(PROTOC) --cpp_out=$(@D) --proto_path=$(<D) $<
|
||||
|
||||
if EMBEDDED_LEVELDB
|
||||
include Makefile.leveldb.include
|
||||
endif
|
||||
|
||||
if ENABLE_TESTS
|
||||
include Makefile.test.include
|
||||
endif
|
||||
|
||||
@@ -41,6 +41,8 @@ bench_bench_bitcoin_LDADD = \
|
||||
$(LIBBITCOIN_UTIL) \
|
||||
$(LIBBITCOIN_CONSENSUS) \
|
||||
$(LIBBITCOIN_CRYPTO) \
|
||||
$(LIBLEVELDB) \
|
||||
$(LIBLEVELDB_SSE42) \
|
||||
$(LIBMEMENV) \
|
||||
$(LIBSECP256K1) \
|
||||
$(LIBUNIVALUE)
|
||||
@@ -53,7 +55,7 @@ if ENABLE_WALLET
|
||||
bench_bench_bitcoin_SOURCES += bench/coin_selection.cpp
|
||||
endif
|
||||
|
||||
bench_bench_bitcoin_LDADD += $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(BDB_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS) $(MINIUPNPC_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
|
||||
bench_bench_bitcoin_LDADD += $(BOOST_LIBS) $(BDB_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS) $(MINIUPNPC_LIBS) $(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
|
||||
bench_bench_bitcoin_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
|
||||
|
||||
CLEAN_BITCOIN_BENCH = bench/*.gcda bench/*.gcno $(GENERATED_BENCH_FILES)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# Copyright (c) 2016 The Bitcoin Core developers
|
||||
# Distributed under the MIT software license, see the accompanying
|
||||
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
LIBLEVELDB_INT = leveldb/libleveldb.a
|
||||
LIBMEMENV_INT = leveldb/libmemenv.a
|
||||
LIBLEVELDB_SSE42_INT = leveldb/libleveldb_sse42.a
|
||||
|
||||
EXTRA_LIBRARIES += $(LIBLEVELDB_INT)
|
||||
EXTRA_LIBRARIES += $(LIBMEMENV_INT)
|
||||
EXTRA_LIBRARIES += $(LIBLEVELDB_SSE42_INT)
|
||||
|
||||
LIBLEVELDB += $(LIBLEVELDB_INT)
|
||||
LIBMEMENV += $(LIBMEMENV_INT)
|
||||
LIBLEVELDB_SSE42 = $(LIBLEVELDB_SSE42_INT)
|
||||
|
||||
LEVELDB_CPPFLAGS += -I$(srcdir)/leveldb/include
|
||||
LEVELDB_CPPFLAGS += -I$(srcdir)/leveldb/helpers/memenv
|
||||
|
||||
LEVELDB_CPPFLAGS_INT =
|
||||
LEVELDB_CPPFLAGS_INT += -I$(srcdir)/leveldb
|
||||
LEVELDB_CPPFLAGS_INT += $(LEVELDB_TARGET_FLAGS)
|
||||
LEVELDB_CPPFLAGS_INT += -DLEVELDB_ATOMIC_PRESENT
|
||||
LEVELDB_CPPFLAGS_INT += -D__STDC_LIMIT_MACROS
|
||||
|
||||
if TARGET_WINDOWS
|
||||
LEVELDB_CPPFLAGS_INT += -DLEVELDB_PLATFORM_WINDOWS -DWINVER=0x0500 -D__USE_MINGW_ANSI_STDIO=1
|
||||
else
|
||||
LEVELDB_CPPFLAGS_INT += -DLEVELDB_PLATFORM_POSIX
|
||||
endif
|
||||
|
||||
leveldb_libleveldb_a_CPPFLAGS = $(AM_CPPFLAGS) $(LEVELDB_CPPFLAGS_INT) $(LEVELDB_CPPFLAGS)
|
||||
leveldb_libleveldb_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
|
||||
|
||||
leveldb_libleveldb_a_SOURCES=
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/atomic_pointer.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/port_example.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/port_posix.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/win/stdint.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/port.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/port_win.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/thread_annotations.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/db.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/options.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/comparator.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/filter_policy.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/slice.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/table_builder.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/env.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/c.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/iterator.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/cache.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/dumpfile.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/table.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/write_batch.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/include/leveldb/status.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/log_format.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/memtable.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/version_set.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/write_batch_internal.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/filename.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/version_edit.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/dbformat.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/builder.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/log_writer.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/db_iter.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/skiplist.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/db_impl.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/table_cache.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/snapshot.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/log_reader.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/filter_block.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/block_builder.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/block.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/two_level_iterator.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/merger.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/format.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/iterator_wrapper.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/crc32c.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/env_posix_test_helper.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/arena.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/random.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/posix_logger.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/hash.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/histogram.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/coding.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/testutil.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/mutexlock.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/logging.h
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/testharness.h
|
||||
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/builder.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/c.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/dbformat.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/db_impl.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/db_iter.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/dumpfile.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/filename.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/log_reader.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/log_writer.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/memtable.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/repair.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/table_cache.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/version_edit.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/version_set.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/db/write_batch.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/block_builder.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/block.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/filter_block.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/format.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/iterator.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/merger.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/table_builder.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/table.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/table/two_level_iterator.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/arena.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/bloom.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/cache.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/coding.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/comparator.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/crc32c.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/env.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/env_posix.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/filter_policy.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/hash.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/histogram.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/logging.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/options.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/status.cc
|
||||
|
||||
if TARGET_WINDOWS
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/util/env_win.cc
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/port_win.cc
|
||||
else
|
||||
leveldb_libleveldb_a_SOURCES += leveldb/port/port_posix.cc
|
||||
endif
|
||||
|
||||
leveldb_libmemenv_a_CPPFLAGS = $(leveldb_libleveldb_a_CPPFLAGS)
|
||||
leveldb_libmemenv_a_CXXFLAGS = $(leveldb_libleveldb_a_CXXFLAGS)
|
||||
leveldb_libmemenv_a_SOURCES = leveldb/helpers/memenv/memenv.cc
|
||||
leveldb_libmemenv_a_SOURCES += leveldb/helpers/memenv/memenv.h
|
||||
|
||||
leveldb_libleveldb_sse42_a_CPPFLAGS = $(leveldb_libleveldb_a_CPPFLAGS)
|
||||
leveldb_libleveldb_sse42_a_CXXFLAGS = $(leveldb_libleveldb_a_CXXFLAGS)
|
||||
if ENABLE_HWCRC32
|
||||
leveldb_libleveldb_sse42_a_CPPFLAGS += -DLEVELDB_PLATFORM_POSIX_SSE
|
||||
leveldb_libleveldb_sse42_a_CXXFLAGS += $(SSE42_CXXFLAGS)
|
||||
endif
|
||||
leveldb_libleveldb_sse42_a_SOURCES = leveldb/port/port_posix_sse.cc
|
||||
@@ -408,8 +408,8 @@ endif
|
||||
if ENABLE_ZMQ
|
||||
qt_lbrycrd_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS)
|
||||
endif
|
||||
qt_lbrycrd_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBMEMENV) \
|
||||
$(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(QT_LIBS) $(QT_DBUS_LIBS) $(QR_LIBS) $(PROTOBUF_LIBS) $(ICU_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(LIBSECP256K1) \
|
||||
qt_lbrycrd_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBLEVELDB) $(LIBLEVELDB_SSE42) $(LIBMEMENV) \
|
||||
$(BOOST_LIBS) $(QT_LIBS) $(QT_DBUS_LIBS) $(QR_LIBS) $(PROTOBUF_LIBS) $(ICU_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(LIBSECP256K1) \
|
||||
$(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
|
||||
qt_lbrycrd_qt_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(QT_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
|
||||
qt_lbrycrd_qt_LIBTOOLFLAGS = $(AM_LIBTOOLFLAGS) --tag CXX
|
||||
@@ -443,10 +443,10 @@ CLEAN_QT = $(nodist_qt_libbitcoinqt_a_SOURCES) $(QT_QM) $(QT_FORMS_H) qt/*.gcda
|
||||
|
||||
CLEANFILES += $(CLEAN_QT)
|
||||
|
||||
lbrycrd_qt_clean: FORCE
|
||||
bitcoin_qt_clean: FORCE
|
||||
rm -f $(CLEAN_QT) $(qt_libbitcoinqt_a_OBJECTS) $(qt_lbrycrd_qt_OBJECTS) qt/lbrycrd-qt$(EXEEXT) $(LIBBITCOINQT)
|
||||
|
||||
lbrycrd_qt : qt/lbrycrd-qt$(EXEEXT)
|
||||
bitcoin_qt : qt/lbrycrd-qt$(EXEEXT)
|
||||
|
||||
ui_%.h: %.ui
|
||||
@test -f $(UIC)
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
bin_PROGRAMS += qt/test/test_lbrycrd-qt
|
||||
TESTS += qt/test/test_lbrycrd-qt
|
||||
TEST_QT_BINARY=qt/test/test_lbrycrd-qt$(EXEEXT)
|
||||
|
||||
TEST_QT_MOC_CPP = \
|
||||
qt/test/moc_compattests.cpp \
|
||||
@@ -63,8 +62,8 @@ endif
|
||||
if ENABLE_ZMQ
|
||||
qt_test_test_lbrycrd_qt_LDADD += $(LIBBITCOIN_ZMQ) $(ZMQ_LIBS)
|
||||
endif
|
||||
qt_test_test_lbrycrd_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) \
|
||||
$(LIBMEMENV) $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(QT_DBUS_LIBS) $(QT_TEST_LIBS) $(QT_LIBS) \
|
||||
qt_test_test_lbrycrd_qt_LDADD += $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) $(LIBLEVELDB) \
|
||||
$(LIBLEVELDB_SSE42) $(LIBMEMENV) $(BOOST_LIBS) $(QT_DBUS_LIBS) $(QT_TEST_LIBS) $(QT_LIBS) \
|
||||
$(QR_LIBS) $(PROTOBUF_LIBS) $(ICU_LIBS) $(BDB_LIBS) $(SSL_LIBS) $(CRYPTO_LIBS) $(MINIUPNPC_LIBS) $(LIBSECP256K1) \
|
||||
$(EVENT_PTHREADS_LIBS) $(EVENT_LIBS)
|
||||
qt_test_test_lbrycrd_qt_LDFLAGS = $(RELDFLAGS) $(AM_LDFLAGS) $(QT_LDFLAGS) $(LIBTOOL_APP_LDFLAGS)
|
||||
@@ -74,10 +73,10 @@ CLEAN_BITCOIN_QT_TEST = $(TEST_QT_MOC_CPP) qt/test/*.gcda qt/test/*.gcno
|
||||
|
||||
CLEANFILES += $(CLEAN_BITCOIN_QT_TEST)
|
||||
|
||||
test_lbrycrd_qt : $(TEST_QT_BINARY)
|
||||
test_lbrycrd_qt : qt/test/test_bitcoin-qt$(EXEEXT)
|
||||
|
||||
test_lbrycrd_qt_check : $(TEST_QT_BINARY) FORCE
|
||||
test_lbrycrd_qt_check : qt/test/test_bitcoin-qt$(EXEEXT) FORCE
|
||||
$(MAKE) check-TESTS TESTS=$^
|
||||
|
||||
test_lbrycrd_qt_clean: FORCE
|
||||
rm -f $(CLEAN_BITCOIN_QT_TEST) $(qt_test_test_lbrycrd_qt_OBJECTS) $(TEST_QT_BINARY)
|
||||
rm -f $(CLEAN_BITCOIN_QT_TEST) $(qt_test_test_lbrycrd_qt_OBJECTS)
|
||||
@@ -45,7 +45,6 @@ BITCOIN_TESTS =\
|
||||
test/bswap_tests.cpp \
|
||||
test/checkqueue_tests.cpp \
|
||||
test/coins_tests.cpp \
|
||||
test/compilerbug_tests.cpp \
|
||||
test/compress_tests.cpp \
|
||||
test/crypto_tests.cpp \
|
||||
test/cuckoocache_tests.cpp \
|
||||
@@ -56,6 +55,7 @@ BITCOIN_TESTS =\
|
||||
test/key_io_tests.cpp \
|
||||
test/key_tests.cpp \
|
||||
test/limitedmap_tests.cpp \
|
||||
test/dbwrapper_tests.cpp \
|
||||
test/main_tests.cpp \
|
||||
test/mempool_tests.cpp \
|
||||
test/merkle_tests.cpp \
|
||||
@@ -65,11 +65,6 @@ BITCOIN_TESTS =\
|
||||
test/net_tests.cpp \
|
||||
test/claimtriecache_tests.cpp \
|
||||
test/claimtriebranching_tests.cpp \
|
||||
test/claimtrieexpirationfork_tests.cpp \
|
||||
test/claimtriefixture.cpp \
|
||||
test/claimtriehashfork_tests.cpp \
|
||||
test/claimtrienormalization_tests.cpp \
|
||||
test/claimtrierpc_tests.cpp \
|
||||
test/nameclaim_tests.cpp \
|
||||
test/netbase_tests.cpp \
|
||||
test/pmt_tests.cpp \
|
||||
@@ -94,6 +89,7 @@ BITCOIN_TESTS =\
|
||||
test/timedata_tests.cpp \
|
||||
test/torcontrol_tests.cpp \
|
||||
test/transaction_tests.cpp \
|
||||
test/txindex_tests.cpp \
|
||||
test/txvalidation_tests.cpp \
|
||||
test/txvalidationcache_tests.cpp \
|
||||
test/uint256_tests.cpp \
|
||||
@@ -124,7 +120,7 @@ test_test_lbrycrd_LDADD += $(LIBBITCOIN_WALLET)
|
||||
endif
|
||||
|
||||
test_test_lbrycrd_LDADD += $(LIBBITCOIN_SERVER) $(LIBBITCOIN_CLI) $(LIBBITCOIN_COMMON) $(LIBBITCOIN_UTIL) $(LIBBITCOIN_CONSENSUS) $(LIBBITCOIN_CRYPTO) $(LIBUNIVALUE) \
|
||||
$(LIBMEMENV) $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(BOOST_UNIT_TEST_FRAMEWORK_LIB) $(LIBSECP256K1) $(EVENT_LIBS) $(EVENT_PTHREADS_LIBS)
|
||||
$(LIBLEVELDB) $(LIBLEVELDB_SSE42) $(LIBMEMENV) $(BOOST_LIBS) $(BOOST_UNIT_TEST_FRAMEWORK_LIB) $(LIBSECP256K1) $(EVENT_LIBS) $(EVENT_PTHREADS_LIBS)
|
||||
test_test_lbrycrd_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
|
||||
|
||||
test_test_lbrycrd_LDADD += $(LIBBITCOIN_CONSENSUS) $(BDB_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS) $(MINIUPNPC_LIBS)
|
||||
@@ -153,7 +149,8 @@ test_test_lbrycrd_fuzzy_LDADD = \
|
||||
$(LIBBITCOIN_CRYPTO_SHANI) \
|
||||
$(LIBSECP256K1)
|
||||
|
||||
test_test_lbrycrd_fuzzy_LDADD += $(BOOST_LIBS) $(LIBCLAIMTRIE) $(BOOST_LOCALE_LIB) $(CRYPTO_LIBS) $(ICU_LIBS)
|
||||
test_test_lbrycrd_fuzzy_LDADD += $(BOOST_LIBS) $(CRYPTO_LIBS) $(ICU_LIBS)
|
||||
#
|
||||
|
||||
nodist_test_test_lbrycrd_SOURCES = $(GENERATED_TEST_FILES)
|
||||
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ bool DeserializeFileDB(const fs::path& path, Data& data)
|
||||
FILE *file = fsbridge::fopen(path, "rb");
|
||||
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
|
||||
if (filein.IsNull())
|
||||
return false;
|
||||
return error("%s: Failed to open file %s", __func__, path.string());
|
||||
|
||||
return DeserializeDB(filein, data);
|
||||
}
|
||||
|
||||
+8
-8
@@ -11,23 +11,23 @@
|
||||
|
||||
int CAddrInfo::GetTriedBucket(const uint256& nKey) const
|
||||
{
|
||||
auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash();
|
||||
auto hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (GetCheapHash(hash1) % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash();
|
||||
return GetCheapHash(hash2) % ADDRMAN_TRIED_BUCKET_COUNT;
|
||||
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash();
|
||||
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash();
|
||||
return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
|
||||
}
|
||||
|
||||
int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const
|
||||
{
|
||||
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
|
||||
auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash();
|
||||
auto hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (GetCheapHash(hash1) % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash();
|
||||
return GetCheapHash(hash2) % ADDRMAN_NEW_BUCKET_COUNT;
|
||||
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash();
|
||||
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash();
|
||||
return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
|
||||
}
|
||||
|
||||
int CAddrInfo::GetBucketPosition(const uint256 &nKey, bool fNew, int nBucket) const
|
||||
{
|
||||
auto hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash();
|
||||
return GetCheapHash(hash1) % ADDRMAN_BUCKET_SIZE;
|
||||
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash();
|
||||
return hash1 % ADDRMAN_BUCKET_SIZE;
|
||||
}
|
||||
|
||||
bool CAddrInfo::IsTerrible(int64_t nNow) const
|
||||
|
||||
+2
-2
@@ -56,8 +56,8 @@ public:
|
||||
{
|
||||
static_assert(BITS/32 > 0 && BITS%32 == 0, "Template parameter BITS must be a positive multiple of 32.");
|
||||
|
||||
pn[0] = uint32_t(b);
|
||||
pn[1] = uint32_t(b >> 32U);
|
||||
pn[0] = (unsigned int)b;
|
||||
pn[1] = (unsigned int)(b >> 32);
|
||||
for (int i = 2; i < WIDTH; i++)
|
||||
pn[i] = 0;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
#include <scheduler.h>
|
||||
#include <txdb.h>
|
||||
#include <txmempool.h>
|
||||
#include <util.h>
|
||||
#include <utiltime.h>
|
||||
#include <validation.h>
|
||||
#include <validationinterface.h>
|
||||
@@ -41,7 +40,7 @@ static CTxIn MineBlock(const CScript& coinbase_scriptPubKey)
|
||||
{
|
||||
auto block = PrepareBlock(coinbase_scriptPubKey);
|
||||
|
||||
while (!CheckProofOfWork(block->GetPoWHash(), block->nBits, Params().GetConsensus())) {
|
||||
while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {
|
||||
++block->nNonce;
|
||||
assert(block->nNonce);
|
||||
}
|
||||
@@ -73,29 +72,18 @@ static void AssembleBlock(benchmark::State& state)
|
||||
boost::thread_group thread_group;
|
||||
CScheduler scheduler;
|
||||
{
|
||||
delete ::pclaimTrie;
|
||||
const CChainParams& chainparams = Params();
|
||||
auto &consensus = chainparams.GetConsensus();
|
||||
::pblocktree.reset(new CBlockTreeDB(1 << 20, true));
|
||||
::pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));
|
||||
::pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));
|
||||
::pclaimTrie = new CClaimTrie(1 << 25, true, 0, GetDataDir().string(),
|
||||
consensus.nNormalizedNameForkHeight,
|
||||
consensus.nMinRemovalWorkaroundHeight,
|
||||
consensus.nMaxRemovalWorkaroundHeight,
|
||||
consensus.nOriginalClaimExpirationTime,
|
||||
consensus.nExtendedClaimExpirationTime,
|
||||
consensus.nExtendedClaimExpirationForkHeight,
|
||||
consensus.nAllClaimsInMerkleForkHeight, 1);
|
||||
|
||||
const CChainParams& chainparams = Params();
|
||||
thread_group.create_thread(boost::bind(&CScheduler::serviceQueue, &scheduler));
|
||||
GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
|
||||
LoadGenesisBlock(chainparams);
|
||||
CValidationState state;
|
||||
ActivateBestChain(state, chainparams);
|
||||
assert(::chainActive.Tip() != nullptr);
|
||||
const_cast<int&>(consensus.nWitnessForkHeight) = ::chainActive.Height();
|
||||
const bool witness_enabled{IsWitnessEnabled(::chainActive.Tip(), consensus)};
|
||||
const bool witness_enabled{IsWitnessEnabled(::chainActive.Tip(), chainparams.GetConsensus())};
|
||||
assert(witness_enabled);
|
||||
}
|
||||
|
||||
|
||||
+15
-48
@@ -9,50 +9,9 @@
|
||||
#include <streams.h>
|
||||
#include <consensus/validation.h>
|
||||
|
||||
|
||||
/* Don't use raw bitcoin blocks
|
||||
namespace block_bench {
|
||||
#include <bench/data/block413567.raw.h>
|
||||
} // namespace block_bench
|
||||
*/
|
||||
|
||||
CDataStream getTestBlockStream()
|
||||
{
|
||||
static CBlock block;
|
||||
static CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
|
||||
if (block.IsNull()) {
|
||||
block.nVersion = 5;
|
||||
block.hashPrevBlock = uint256S("e8fc54d1e6581fceaaf64cc8afeedb9c4ba1eb2349eaf638f1fc41e331869dee");
|
||||
block.hashMerkleRoot = uint256S("a926580973e1204aa179a4c536023c69212ce00b56dc85d3516488f3c51dd022");
|
||||
block.hashClaimTrie = uint256S("7bae80d60b09031265f8a9f6282e4b9653764fadfac2c8b4c1f416c972b58814");
|
||||
block.nTime = 1545050539;
|
||||
block.nBits = 0x207fffff;
|
||||
block.nNonce = 128913;
|
||||
block.vtx.resize(60);
|
||||
uint256 prevHash;
|
||||
for (int i = 0; i < 60; ++i) {
|
||||
CMutableTransaction tx;
|
||||
tx.nVersion = 5;
|
||||
tx.nLockTime = 0;
|
||||
tx.vin.resize(1);
|
||||
tx.vout.resize(1);
|
||||
if (!prevHash.IsNull()) {
|
||||
tx.vin[0].prevout.hash = prevHash;
|
||||
tx.vin[0].prevout.n = 0;
|
||||
}
|
||||
tx.vin[0].scriptSig = CScript() << OP_0 << OP_0;
|
||||
tx.vin[0].nSequence = std::numeric_limits<unsigned int>::max();
|
||||
tx.vout[0].scriptPubKey = CScript();
|
||||
tx.vout[0].nValue = 0;
|
||||
prevHash = tx.GetHash();
|
||||
block.vtx[i] = MakeTransactionRef(std::move(tx));
|
||||
}
|
||||
stream << block;
|
||||
char a = '\0';
|
||||
stream.write(&a, 1); // Prevent compaction
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
// These are the two major time-sinks which happen after we have fully received
|
||||
// a block off the wire, but before we can relay the block on to peers using
|
||||
@@ -60,25 +19,33 @@ CDataStream getTestBlockStream()
|
||||
|
||||
static void DeserializeBlockTest(benchmark::State& state)
|
||||
{
|
||||
auto stream = getTestBlockStream();
|
||||
const auto size = stream.size() - 1;
|
||||
CDataStream stream((const char*)block_bench::block413567,
|
||||
(const char*)&block_bench::block413567[sizeof(block_bench::block413567)],
|
||||
SER_NETWORK, PROTOCOL_VERSION);
|
||||
char a = '\0';
|
||||
stream.write(&a, 1); // Prevent compaction
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
CBlock block;
|
||||
stream >> block;
|
||||
assert(stream.Rewind(size));
|
||||
assert(stream.Rewind(sizeof(block_bench::block413567)));
|
||||
}
|
||||
}
|
||||
|
||||
static void DeserializeAndCheckBlockTest(benchmark::State& state)
|
||||
{
|
||||
auto stream = getTestBlockStream();
|
||||
const auto size = stream.size() - 1;
|
||||
const auto chainParams = CreateChainParams(CBaseChainParams::REGTEST);
|
||||
CDataStream stream((const char*)block_bench::block413567,
|
||||
(const char*)&block_bench::block413567[sizeof(block_bench::block413567)],
|
||||
SER_NETWORK, PROTOCOL_VERSION);
|
||||
char a = '\0';
|
||||
stream.write(&a, 1); // Prevent compaction
|
||||
|
||||
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
|
||||
|
||||
while (state.KeepRunning()) {
|
||||
CBlock block; // Note that CBlock caches its checked state, so we need to recreate it here
|
||||
stream >> block;
|
||||
assert(stream.Rewind(size));
|
||||
assert(stream.Rewind(sizeof(block_bench::block413567)));
|
||||
|
||||
CValidationState validationState;
|
||||
assert(CheckBlock(block, validationState, chainParams->GetConsensus()));
|
||||
|
||||
@@ -4,13 +4,11 @@
|
||||
|
||||
#include <bench/bench.h>
|
||||
|
||||
#include <claimtrie/hashes.h>
|
||||
#include <consensus/merkle.h>
|
||||
#include <crypto/sha256.h>
|
||||
#include <random.h>
|
||||
#include <uint256.h>
|
||||
#include <random.h>
|
||||
#include <consensus/merkle.h>
|
||||
|
||||
static void MerkleRootUni(benchmark::State& state)
|
||||
static void MerkleRoot(benchmark::State& state)
|
||||
{
|
||||
FastRandomContext rng(true);
|
||||
std::vector<uint256> leaves;
|
||||
@@ -20,18 +18,9 @@ static void MerkleRootUni(benchmark::State& state)
|
||||
}
|
||||
while (state.KeepRunning()) {
|
||||
bool mutation = false;
|
||||
uint256 hash = ComputeMerkleRoot(leaves, &mutation);
|
||||
uint256 hash = ComputeMerkleRoot(std::vector<uint256>(leaves), &mutation);
|
||||
leaves[mutation] = hash;
|
||||
}
|
||||
}
|
||||
|
||||
static void MerkleRoot(benchmark::State& state)
|
||||
{
|
||||
sha256n_way = [](std::vector<uint256>& hashes) {
|
||||
SHA256D64(hashes[0].begin(), hashes[0].begin(), hashes.size() / 2);
|
||||
};
|
||||
MerkleRootUni(state);
|
||||
}
|
||||
|
||||
BENCHMARK(MerkleRoot, 800);
|
||||
BENCHMARK(MerkleRootUni, 800);
|
||||
@@ -3,7 +3,6 @@
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <bloom.h>
|
||||
#include <nameclaim.h>
|
||||
|
||||
#include <primitives/transaction.h>
|
||||
#include <hash.h>
|
||||
|
||||
+67
@@ -376,6 +376,73 @@ int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& fr
|
||||
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb);
|
||||
|
||||
|
||||
/** Used to marshal pointers into hashes for db storage. */
|
||||
class CDiskBlockIndex : public CBlockIndex
|
||||
{
|
||||
public:
|
||||
uint256 hashPrev;
|
||||
|
||||
CDiskBlockIndex() {
|
||||
hashPrev = uint256();
|
||||
}
|
||||
|
||||
explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
|
||||
hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
|
||||
}
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action) {
|
||||
int _nVersion = s.GetVersion();
|
||||
if (!(s.GetType() & SER_GETHASH))
|
||||
READWRITE(VARINT(_nVersion, VarIntMode::NONNEGATIVE_SIGNED));
|
||||
|
||||
READWRITE(VARINT(nHeight, VarIntMode::NONNEGATIVE_SIGNED));
|
||||
READWRITE(VARINT(nStatus));
|
||||
READWRITE(VARINT(nTx));
|
||||
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
|
||||
READWRITE(VARINT(nFile, VarIntMode::NONNEGATIVE_SIGNED));
|
||||
if (nStatus & BLOCK_HAVE_DATA)
|
||||
READWRITE(VARINT(nDataPos));
|
||||
if (nStatus & BLOCK_HAVE_UNDO)
|
||||
READWRITE(VARINT(nUndoPos));
|
||||
|
||||
// block header
|
||||
READWRITE(this->nVersion);
|
||||
READWRITE(hashPrev);
|
||||
READWRITE(hashMerkleRoot);
|
||||
READWRITE(hashClaimTrie);
|
||||
READWRITE(nTime);
|
||||
READWRITE(nBits);
|
||||
READWRITE(nNonce);
|
||||
}
|
||||
|
||||
uint256 GetBlockHash() const
|
||||
{
|
||||
CBlockHeader block;
|
||||
block.nVersion = nVersion;
|
||||
block.hashPrevBlock = hashPrev;
|
||||
block.hashMerkleRoot = hashMerkleRoot;
|
||||
block.hashClaimTrie = hashClaimTrie;
|
||||
block.nTime = nTime;
|
||||
block.nBits = nBits;
|
||||
block.nNonce = nNonce;
|
||||
return block.GetHash();
|
||||
}
|
||||
|
||||
std::string ToString() const
|
||||
{
|
||||
std::string str = "CDiskBlockIndex(";
|
||||
str += CBlockIndex::ToString();
|
||||
str += strprintf("\n hashBlock=%s, hashClaimTrie=%s, hashPrev=%s)",
|
||||
GetBlockHash().ToString(),
|
||||
hashClaimTrie.ToString(),
|
||||
hashPrev.ToString());
|
||||
return str;
|
||||
}
|
||||
};
|
||||
|
||||
/** An in-memory indexed chain of blocks. */
|
||||
class CChain {
|
||||
private:
|
||||
|
||||
+15
-26
@@ -123,7 +123,7 @@ void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64
|
||||
class CMainParams : public CChainParams {
|
||||
public:
|
||||
CMainParams() {
|
||||
strNetworkID = CBaseChainParams::MAIN;
|
||||
strNetworkID = "lbrycrd";
|
||||
consensus.nSubsidyLevelInterval = 1<<5;
|
||||
consensus.nMajorityEnforceBlockUpgrade = 750;
|
||||
consensus.nMajorityRejectBlockOutdated = 950;
|
||||
@@ -132,8 +132,8 @@ public:
|
||||
consensus.BIP34Height = 1;
|
||||
consensus.BIP34Hash = uint256S("0xdecb9e2cca03a419fd9cca0cb2b1d5ad11b088f22f8f38556d93ac4358b86c24");
|
||||
// FIXME: adjust heights
|
||||
consensus.BIP65Height = 200000;
|
||||
consensus.BIP66Height = 200000;
|
||||
consensus.BIP65Height = 600000;
|
||||
consensus.BIP66Height = 600000;
|
||||
consensus.powLimit = uint256S("0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
|
||||
consensus.nPowTargetTimespan = 150; //retarget every block
|
||||
consensus.nPowTargetSpacing = 150;
|
||||
@@ -143,14 +143,10 @@ public:
|
||||
consensus.nAllowMinDiffMinHeight = -1;
|
||||
consensus.nAllowMinDiffMaxHeight = -1;
|
||||
consensus.nNormalizedNameForkHeight = 539940; // targeting 21 March 2019
|
||||
consensus.nMinRemovalWorkaroundHeight = 297706;
|
||||
consensus.nMaxRemovalWorkaroundHeight = 100000000;
|
||||
consensus.nWitnessForkHeight = 680770; // targeting 11 Dec 2019
|
||||
consensus.nAllClaimsInMerkleForkHeight = 658310; // targeting 30 Oct 2019
|
||||
consensus.fPowAllowMinDifficultyBlocks = false;
|
||||
consensus.fPowNoRetargeting = false;
|
||||
consensus.nRuleChangeActivationThreshold = 1916; // 95% of a half week
|
||||
consensus.nMinerConfirmationWindow = 2016;
|
||||
consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016
|
||||
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
|
||||
@@ -160,16 +156,17 @@ public:
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
|
||||
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147) -- Unused (see nWitnessForkHeight).
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147)
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1547942400; // Jan 20, 2019
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1548288000; // Jan 24, 2019
|
||||
|
||||
// The best chain should have at least this much work.
|
||||
consensus.nMinimumChainWork = uint256S("00000000000000000000000000000000000000000000024108e3204a44a57a5a"); //621000
|
||||
consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000000000607ca7e806c4c1e9"); //400000
|
||||
|
||||
// By default assume that the signatures in ancestors of this block are valid.
|
||||
consensus.defaultAssumeValid = uint256S("7899464514d0d8854919e87eb234fd5f0c35d06418bd5fd3c1a8f7092b2a9317"); //620000
|
||||
//consensus.defaultAssumeValid = uint256S("0xf0e56e70782af63ccb49c76e852540688755869ba59ec68cac9c04a6b4d9f5ca"); //400000
|
||||
consensus.defaultAssumeValid = uint256S("0xa6bbb48f5343eb9b0287c22f3ea8b29f36cf10794a37f8a925a894d6f4519913"); //4000
|
||||
|
||||
/**
|
||||
* The message start string is designed to be unlikely to occur in normal data.
|
||||
@@ -207,7 +204,7 @@ public:
|
||||
|
||||
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
|
||||
|
||||
bech32_hrp = "lbc";
|
||||
bech32_hrp = "bc";
|
||||
|
||||
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
|
||||
|
||||
@@ -241,7 +238,7 @@ public:
|
||||
class CTestNetParams : public CChainParams {
|
||||
public:
|
||||
CTestNetParams() {
|
||||
strNetworkID = CBaseChainParams::TESTNET;
|
||||
strNetworkID = "lbrycrdtest";
|
||||
consensus.nSubsidyLevelInterval = 1 << 5;
|
||||
consensus.nMajorityEnforceBlockUpgrade = 51;
|
||||
consensus.nMajorityRejectBlockOutdated = 75;
|
||||
@@ -261,10 +258,6 @@ public:
|
||||
consensus.nAllowMinDiffMinHeight = 277299;
|
||||
consensus.nAllowMinDiffMaxHeight = 1100000;
|
||||
consensus.nNormalizedNameForkHeight = 993380; // targeting, 21 Feb 2019
|
||||
consensus.nMinRemovalWorkaroundHeight = 99;
|
||||
consensus.nMaxRemovalWorkaroundHeight = 100000000;
|
||||
consensus.nWitnessForkHeight = 1198600;
|
||||
consensus.nAllClaimsInMerkleForkHeight = 1198560; // targeting 30 Sep 2019
|
||||
consensus.fPowAllowMinDifficultyBlocks = true;
|
||||
consensus.fPowNoRetargeting = false;
|
||||
consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
|
||||
@@ -278,7 +271,7 @@ public:
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
|
||||
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147) -- Unused (see nWitnessForkHeight).
|
||||
// Deployment of SegWit (BIP141, BIP143, and BIP147)
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016
|
||||
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017
|
||||
@@ -317,7 +310,7 @@ public:
|
||||
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
|
||||
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
|
||||
|
||||
bech32_hrp = "tlbc";
|
||||
bech32_hrp = "tb";
|
||||
|
||||
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
|
||||
|
||||
@@ -351,7 +344,7 @@ public:
|
||||
class CRegTestParams : public CChainParams {
|
||||
public:
|
||||
CRegTestParams() {
|
||||
strNetworkID = CBaseChainParams::REGTEST;
|
||||
strNetworkID = "lbrycrdreg";
|
||||
consensus.nSubsidyLevelInterval = 1 << 5;
|
||||
consensus.BIP16Exception = uint256();
|
||||
consensus.BIP34Height = 1000; // BIP34 is needed for validation_block_tests
|
||||
@@ -368,10 +361,6 @@ public:
|
||||
consensus.nAllowMinDiffMinHeight = -1;
|
||||
consensus.nAllowMinDiffMaxHeight = -1;
|
||||
consensus.nNormalizedNameForkHeight = 250; // SDK depends upon this number
|
||||
consensus.nMinRemovalWorkaroundHeight = -1;
|
||||
consensus.nMaxRemovalWorkaroundHeight = -1;
|
||||
consensus.nWitnessForkHeight = 150;
|
||||
consensus.nAllClaimsInMerkleForkHeight = 350;
|
||||
consensus.fPowAllowMinDifficultyBlocks = false;
|
||||
consensus.fPowNoRetargeting = false;
|
||||
consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
|
||||
@@ -436,7 +425,7 @@ public:
|
||||
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
|
||||
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
|
||||
|
||||
bech32_hrp = "rlbc";
|
||||
bech32_hrp = "bcrt";
|
||||
|
||||
/* enable fallback fee on regtest */
|
||||
m_fallback_fee_enabled = true;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
const std::string CBaseChainParams::MAIN = "lbrycrd";
|
||||
const std::string CBaseChainParams::TESTNET = "lbrycrdtest";
|
||||
const std::string CBaseChainParams::REGTEST = "lbrycrdreg";
|
||||
const std::string CBaseChainParams::REGTEST = "regtest";
|
||||
|
||||
void SetupChainParamsBaseOptions()
|
||||
{
|
||||
|
||||
+66
-125
@@ -2,9 +2,8 @@
|
||||
// Distributed under the MIT software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <coins.h>
|
||||
#include <claimscriptop.h>
|
||||
#include <nameclaim.h>
|
||||
#include "claimscriptop.h"
|
||||
#include "nameclaim.h"
|
||||
|
||||
CClaimScriptAddOp::CClaimScriptAddOp(const COutPoint& point, CAmount nValue, int nHeight)
|
||||
: point(point), nValue(nValue), nHeight(nHeight)
|
||||
@@ -13,30 +12,22 @@ CClaimScriptAddOp::CClaimScriptAddOp(const COutPoint& point, CAmount nValue, int
|
||||
|
||||
bool CClaimScriptAddOp::claimName(CClaimTrieCache& trieCache, const std::string& name)
|
||||
{
|
||||
auto claimId = ClaimIdHash(point.hash, point.n);
|
||||
LogPrint(BCLog::CLAIMS, "+++ Claim added: %s, c: %.6s, t: %.6s:%d, h: %.6d, a: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValue);
|
||||
return addClaim(trieCache, name, claimId, -1, -1);
|
||||
return addClaim(trieCache, name, ClaimIdHash(point.hash, point.n));
|
||||
}
|
||||
|
||||
bool CClaimScriptAddOp::updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
LogPrint(BCLog::CLAIMS, "+++ Claim updated: %s, c: %.6s, t: %.6s:%d, h: %.6d, a: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValue);
|
||||
return addClaim(trieCache, name, claimId, -1, -1);
|
||||
return addClaim(trieCache, name, claimId);
|
||||
}
|
||||
|
||||
bool CClaimScriptAddOp::addClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId,
|
||||
int takeoverHeight, int originalHeight)
|
||||
bool CClaimScriptAddOp::addClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
return trieCache.addClaim(name, point, claimId, nValue, nHeight, takeoverHeight, originalHeight);
|
||||
return trieCache.addClaim(name, point, claimId, nValue, nHeight);
|
||||
}
|
||||
|
||||
bool CClaimScriptAddOp::supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
LogPrint(BCLog::CLAIMS, "+++ Support added: %s, c: %.6s, t: %.6s:%d, h: %.6d, a: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValue);
|
||||
return trieCache.addSupport(name, point, claimId, nValue, nHeight, -1);
|
||||
return trieCache.addSupport(name, point, nValue, claimId, nHeight);
|
||||
}
|
||||
|
||||
CClaimScriptUndoAddOp::CClaimScriptUndoAddOp(const COutPoint& point, int nHeight) : point(point), nHeight(nHeight)
|
||||
@@ -46,39 +37,32 @@ CClaimScriptUndoAddOp::CClaimScriptUndoAddOp(const COutPoint& point, int nHeight
|
||||
bool CClaimScriptUndoAddOp::claimName(CClaimTrieCache& trieCache, const std::string& name)
|
||||
{
|
||||
auto claimId = ClaimIdHash(point.hash, point.n);
|
||||
LogPrint(BCLog::CLAIMS, "--- Undoing claim add: %s, c: %.6s, t: %.6s:%d, h: %.6d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight);
|
||||
LogPrintf("--- [%lu]: OP_CLAIM_NAME \"%s\" with claimId %s and tx prevout %s at index %d\n", nHeight, name, claimId.GetHex(), point.hash.ToString(), point.n);
|
||||
return undoAddClaim(trieCache, name, claimId);
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoAddOp::updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
LogPrint(BCLog::CLAIMS, "--- Undoing claim update: %s, c: %.6s, t: %.6s:%d, h: %.6d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight);
|
||||
LogPrintf("--- [%lu]: OP_UPDATE_CLAIM \"%s\" with claimId %s and tx prevout %s at index %d\n", nHeight, name, claimId.GetHex(), point.hash.ToString(), point.n);
|
||||
return undoAddClaim(trieCache, name, claimId);
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoAddOp::undoAddClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
std::string nodeName;
|
||||
int validHeight, originalHeight;
|
||||
bool res = trieCache.removeClaim(claimId, point, nodeName, validHeight, originalHeight);
|
||||
LogPrintf("%s: (txid: %s, nOut: %d) Removing %s, claimId: %s, from the claim trie due to block disconnect\n", __func__, point.hash.ToString(), point.n, name, claimId.ToString());
|
||||
bool res = trieCache.undoAddClaim(name, point, nHeight);
|
||||
if (!res)
|
||||
LogPrint(BCLog::CLAIMS, "Remove claim failed for %s (%s) with claimID %.6s, t:%.6s:%d\n", name, nodeName,
|
||||
claimId.GetHex(), point.hash.GetHex(), point.n);
|
||||
LogPrintf("%s: Removing fails\n", __func__);
|
||||
return res;
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoAddOp::supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
LogPrint(BCLog::CLAIMS, "--- Undoing support add: %s, c: %.6s, t: %.6s:%d, h: %.6d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight);
|
||||
std::string nodeName;
|
||||
int validHeight;
|
||||
bool res = trieCache.removeSupport(point, nodeName, validHeight);
|
||||
LogPrintf("--- [%lu]: OP_SUPPORT_CLAIM \"%s\" with claimId %s and tx prevout %s at index %d\n", nHeight, name, claimId.GetHex(), point.hash.ToString(), point.n);
|
||||
LogPrintf("%s: (txid: %s, nOut: %d) Removing support for %s, claimId: %s, from the claim trie due to block disconnect\n", __func__, point.hash.ToString(), point.n, name, claimId.ToString());
|
||||
bool res = trieCache.undoAddSupport(name, point, nHeight);
|
||||
if (!res)
|
||||
LogPrint(BCLog::CLAIMS, "Remove support failed for %s with claimID %.6s, t:%.6s:%d\n", name,
|
||||
claimId.GetHex(), point.hash.GetHex(), point.n);
|
||||
LogPrintf("%s: Removing support fails\n", __func__);
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -90,71 +74,60 @@ CClaimScriptSpendOp::CClaimScriptSpendOp(const COutPoint& point, int nHeight, in
|
||||
bool CClaimScriptSpendOp::claimName(CClaimTrieCache& trieCache, const std::string& name)
|
||||
{
|
||||
auto claimId = ClaimIdHash(point.hash, point.n);
|
||||
auto ret = spendClaim(trieCache, name, claimId);
|
||||
LogPrint(BCLog::CLAIMS, "--- Spent original claim: %s, c: %.6s, t: %.6s:%d, h: %.6d, vh: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValidHeight);
|
||||
return ret;
|
||||
LogPrintf("+++ [%lu]: OP_CLAIM_NAME \"%s\" with claimId %s and tx prevout %s at index %d\n", nHeight, name, claimId.GetHex(), point.hash.ToString(), point.n);
|
||||
return spendClaim(trieCache, name, claimId);
|
||||
}
|
||||
|
||||
bool CClaimScriptSpendOp::updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
auto ret = spendClaim(trieCache, name, claimId);
|
||||
LogPrint(BCLog::CLAIMS, "--- Spent updated claim: %s, c: %.6s, t: %.6s:%d, h: %.6d, vh: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValidHeight);
|
||||
return ret;
|
||||
LogPrintf("+++ [%lu]: OP_UPDATE_CLAIM \"%s\" with claimId %s and tx prevout %s at index %d\n", nHeight, name, claimId.GetHex(), point.hash.ToString(), point.n);
|
||||
return spendClaim(trieCache, name, claimId);
|
||||
}
|
||||
|
||||
bool CClaimScriptSpendOp::spendClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
std::string nodeName;
|
||||
bool res = trieCache.removeClaim(claimId, point, nodeName, nValidHeight, nOriginalHeight);
|
||||
LogPrintf("%s: (txid: %s, nOut: %d) Removing %s, claimId: %s, from the claim trie\n", __func__, point.hash.ToString(), point.n, name, claimId.ToString());
|
||||
bool res = trieCache.spendClaim(name, point, nHeight, nValidHeight);
|
||||
if (!res)
|
||||
LogPrint(BCLog::CLAIMS, "Remove claim failed for %s with claimid %s\n", name, claimId.GetHex().substr(0, 6));
|
||||
LogPrintf("%s: Removing fails\n", __func__);
|
||||
return res;
|
||||
}
|
||||
|
||||
bool CClaimScriptSpendOp::supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
std::string nodeName;
|
||||
bool res = trieCache.removeSupport(point, nodeName, nValidHeight);
|
||||
LogPrint(BCLog::CLAIMS, "--- Spent support: %s, c: %.6s, t: %.6s:%d, h: %.6d, vh: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValidHeight);
|
||||
LogPrintf("+++ [%lu]: OP_SUPPORT_CLAIM \"%s\" with claimId %s and tx prevout %s at index %d\n", nHeight, name, claimId.GetHex(), point.hash.ToString(), point.n);
|
||||
LogPrintf("%s: (txid: %s, nOut: %d) Restoring support for %s, claimId: %s, to the claim trie\n", __func__, point.hash.ToString(), point.n, name, claimId.ToString());
|
||||
bool res = trieCache.spendSupport(name, point, nHeight, nValidHeight);
|
||||
if (!res)
|
||||
LogPrint(BCLog::CLAIMS, "Remove support failed for %s with claimid %s\n", name, claimId.GetHex().substr(0, 6));
|
||||
LogPrintf("%s: Removing support fails\n", __func__);
|
||||
return res;
|
||||
}
|
||||
|
||||
CClaimScriptUndoSpendOp::CClaimScriptUndoSpendOp(const COutPoint& point, CAmount nValue, int nHeight, int nValidHeight, int nOriginalHeight)
|
||||
: point(point), nValue(nValue), nHeight(nHeight), nValidHeight(nValidHeight), nOriginalHeight(nOriginalHeight)
|
||||
CClaimScriptUndoSpendOp::CClaimScriptUndoSpendOp(const COutPoint& point, CAmount nValue, int nHeight, int nValidHeight)
|
||||
: point(point), nValue(nValue), nHeight(nHeight), nValidHeight(nValidHeight)
|
||||
{
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoSpendOp::claimName(CClaimTrieCache& trieCache, const std::string& name)
|
||||
{
|
||||
auto claimId = ClaimIdHash(point.hash, point.n);
|
||||
LogPrint(BCLog::CLAIMS, "+++ Undoing original claim spend: %s, c: %.6s, t: %.6s:%d, h: %.6d, vh: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValidHeight);
|
||||
return undoSpendClaim(trieCache, name, claimId);
|
||||
return undoSpendClaim(trieCache, name, ClaimIdHash(point.hash, point.n));
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoSpendOp::updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
LogPrint(BCLog::CLAIMS, "+++ Undoing updated claim spend: %s, c: %.6s, t: %.6s:%d, h: %.6d, vh: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValidHeight);
|
||||
return undoSpendClaim(trieCache, name, claimId);
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoSpendOp::undoSpendClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
return trieCache.addClaim(name, point, claimId, nValue, nHeight,
|
||||
nValidHeight, nOriginalHeight);
|
||||
LogPrintf("%s: (txid: %s, nOut: %d) Restoring %s, claimId: %s, to the claim trie due to block disconnect\n", __func__, point.hash.ToString(), point.n, name, claimId.ToString());
|
||||
return trieCache.undoSpendClaim(name, point, claimId, nValue, nHeight, nValidHeight);
|
||||
}
|
||||
|
||||
bool CClaimScriptUndoSpendOp::supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId)
|
||||
{
|
||||
LogPrint(BCLog::CLAIMS, "+++ Undoing support spend: %s, c: %.6s, t: %.6s:%d, h: %.6d, vh: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValidHeight);
|
||||
return trieCache.addSupport(name, point, claimId, nValue, nHeight, nValidHeight);
|
||||
LogPrintf("%s: (txid: %s, nOut: %d) Restoring support for %s, claimId: %s, to the claim trie due to block disconnect\n", __func__, point.hash.ToString(), point.n, name, claimId.ToString());
|
||||
return trieCache.undoSpendSupport(name, point, claimId, nValue, nHeight, nValidHeight);
|
||||
}
|
||||
|
||||
static std::string vchToString(const std::vector<unsigned char>& name)
|
||||
@@ -166,7 +139,7 @@ bool ProcessClaim(CClaimScriptOp& claimOp, CClaimTrieCache& trieCache, const CSc
|
||||
{
|
||||
int op;
|
||||
std::vector<std::vector<unsigned char> > vvchParams;
|
||||
if (!DecodeClaimScript(scriptPubKey, op, vvchParams, trieCache.allowSupportMetadata()))
|
||||
if (!DecodeClaimScript(scriptPubKey, op, vvchParams))
|
||||
return false;
|
||||
|
||||
switch (op) {
|
||||
@@ -176,95 +149,63 @@ bool ProcessClaim(CClaimScriptOp& claimOp, CClaimTrieCache& trieCache, const CSc
|
||||
return claimOp.supportClaim(trieCache, vchToString(vvchParams[0]), uint160(vvchParams[1]));
|
||||
case OP_UPDATE_CLAIM:
|
||||
return claimOp.updateClaim(trieCache, vchToString(vvchParams[0]), uint160(vvchParams[1]));
|
||||
default:
|
||||
throw std::runtime_error("Unimplemented OP handler.");
|
||||
}
|
||||
throw std::runtime_error("Unimplemented OP handler.");
|
||||
}
|
||||
|
||||
void UpdateCache(const CTransaction& tx, CClaimTrieCache& trieCache, const CCoinsViewCache& view, int nHeight, const CUpdateCacheCallbacks& callbacks)
|
||||
bool SpendClaim(CClaimTrieCache& trieCache, const CScript& scriptPubKey, const COutPoint& point, int nHeight, int& nValidHeight, spentClaimsType& spentClaims)
|
||||
{
|
||||
class CSpendClaimHistory : public CClaimScriptSpendOp
|
||||
{
|
||||
public:
|
||||
using CClaimScriptSpendOp::CClaimScriptSpendOp;
|
||||
CSpendClaimHistory(spentClaimsType& spentClaims, const COutPoint& point, int nHeight, int& nValidHeight)
|
||||
: CClaimScriptSpendOp(point, nHeight, nValidHeight), spentClaims(spentClaims)
|
||||
{
|
||||
}
|
||||
|
||||
bool spendClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override
|
||||
{
|
||||
if (CClaimScriptSpendOp::spendClaim(trieCache, name, claimId)) {
|
||||
assert(nOriginalHeight >= 0);
|
||||
callback(name, claimId, nOriginalHeight);
|
||||
spentClaims.emplace_back(name, claimId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
std::function<void(const std::string& name, const uint160& claimId, int originalHeight)> callback;
|
||||
|
||||
private:
|
||||
spentClaimsType& spentClaims;
|
||||
};
|
||||
|
||||
spentClaimsType spentClaims;
|
||||
|
||||
for (uint32_t j = 0; j < tx.vin.size(); j++) {
|
||||
const CTxIn& txin = tx.vin[j];
|
||||
const Coin& coin = view.AccessCoin(txin.prevout);
|
||||
|
||||
CScript scriptPubKey;
|
||||
int scriptHeight = nHeight;
|
||||
if (coin.out.IsNull() && callbacks.findScriptKey) {
|
||||
scriptPubKey = callbacks.findScriptKey(txin.prevout);
|
||||
} else {
|
||||
scriptHeight = coin.nHeight;
|
||||
scriptPubKey = coin.out.scriptPubKey;
|
||||
}
|
||||
|
||||
if (scriptPubKey.empty())
|
||||
continue;
|
||||
|
||||
int nValidAtHeight, nOriginalHeight = 0;
|
||||
CSpendClaimHistory spendClaim(COutPoint(txin.prevout.hash, txin.prevout.n), scriptHeight, nValidAtHeight);
|
||||
spendClaim.callback = [&spentClaims, &nOriginalHeight](const std::string& name, const uint160& claimId, int originalHeight) {
|
||||
spentClaims.push_back({name, claimId, originalHeight});
|
||||
nOriginalHeight = originalHeight;
|
||||
};
|
||||
if (ProcessClaim(spendClaim, trieCache, scriptPubKey) && callbacks.claimUndoHeights) {
|
||||
// assert(nValidAtHeight > 0 && nOriginalHeight > 0); // fails on tests
|
||||
callbacks.claimUndoHeights(j, uint32_t(nValidAtHeight), uint32_t(nOriginalHeight));
|
||||
}
|
||||
}
|
||||
CSpendClaimHistory spendClaim(spentClaims, point, nHeight, nValidHeight);
|
||||
return ProcessClaim(spendClaim, trieCache, scriptPubKey);
|
||||
}
|
||||
|
||||
bool AddSpendClaim(CClaimTrieCache& trieCache, const CScript& scriptPubKey, const COutPoint& point, CAmount nValue, int nHeight, spentClaimsType& spentClaims)
|
||||
{
|
||||
class CAddSpendClaim : public CClaimScriptAddOp
|
||||
{
|
||||
public:
|
||||
using CClaimScriptAddOp::CClaimScriptAddOp;
|
||||
CAddSpendClaim(spentClaimsType& spentClaims, const COutPoint& point, CAmount nValue, int nHeight)
|
||||
: CClaimScriptAddOp(point, nValue, nHeight), spentClaims(spentClaims)
|
||||
{
|
||||
}
|
||||
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override
|
||||
{
|
||||
auto originalHeight = callback(name, claimId);
|
||||
if (originalHeight >= 0) {
|
||||
LogPrint(BCLog::CLAIMS, "+++ Claim updated: %s, c: %.6s, t: %.6s:%d, h: %.6d, a: %d\n",
|
||||
name, claimId.GetHex(), point.hash.GetHex(), point.n, nHeight, nValue);
|
||||
return CClaimScriptAddOp::addClaim(trieCache, name, claimId, -1, originalHeight);
|
||||
spentClaimsType::iterator itSpent = spentClaims.begin();
|
||||
for (; itSpent != spentClaims.end(); ++itSpent) {
|
||||
if (itSpent->second == claimId && trieCache.normalizeClaimName(name) == trieCache.normalizeClaimName(itSpent->first)) {
|
||||
spentClaims.erase(itSpent);
|
||||
return CClaimScriptAddOp::updateClaim(trieCache, name, claimId);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
std::function<int(const std::string& name, const uint160& claimId)> callback;
|
||||
|
||||
private:
|
||||
spentClaimsType& spentClaims;
|
||||
};
|
||||
|
||||
for (std::size_t j = 0; j < tx.vout.size(); j++) {
|
||||
const CTxOut& txout = tx.vout[j];
|
||||
|
||||
if (txout.scriptPubKey.empty())
|
||||
continue;
|
||||
|
||||
CAddSpendClaim addClaim(COutPoint(tx.GetHash(), j), txout.nValue, nHeight);
|
||||
addClaim.callback = [&trieCache, &spentClaims](const std::string& name, const uint160& claimId) -> int {
|
||||
for (auto itSpent = spentClaims.begin(); itSpent != spentClaims.end(); ++itSpent) {
|
||||
if (itSpent->id == claimId && trieCache.normalizeClaimName(name) == trieCache.normalizeClaimName(itSpent->name)) {
|
||||
spentClaims.erase(itSpent);
|
||||
assert(itSpent->originalHeight >= 0);
|
||||
return itSpent->originalHeight;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
ProcessClaim(addClaim, trieCache, txout.scriptPubKey);
|
||||
}
|
||||
}
|
||||
CAddSpendClaim addClaim(spentClaims, point, nValue, nHeight);
|
||||
return ProcessClaim(addClaim, trieCache, scriptPubKey);
|
||||
}
|
||||
+33
-30
@@ -6,7 +6,7 @@
|
||||
#define CLAIMSCRIPTOP_H
|
||||
|
||||
#include "amount.h"
|
||||
#include "claimtrie/forks.h"
|
||||
#include "claimtrie.h"
|
||||
#include "hash.h"
|
||||
#include "primitives/transaction.h"
|
||||
#include "script/script.h"
|
||||
@@ -22,7 +22,7 @@
|
||||
class CClaimScriptOp
|
||||
{
|
||||
public:
|
||||
virtual ~CClaimScriptOp() = default;
|
||||
virtual ~CClaimScriptOp() {}
|
||||
/**
|
||||
* Pure virtual, OP_CLAIM_NAME handler
|
||||
* @param[in] trieCache trie to operate on
|
||||
@@ -59,17 +59,17 @@ public:
|
||||
*/
|
||||
CClaimScriptAddOp(const COutPoint& point, CAmount nValue, int nHeight);
|
||||
/**
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -81,8 +81,7 @@ protected:
|
||||
* @param[in] name name of the claim
|
||||
* @param[in] claimId id of the claim
|
||||
*/
|
||||
virtual bool addClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId,
|
||||
int takeoverHeight, int originalHeight);
|
||||
virtual bool addClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId);
|
||||
const COutPoint point;
|
||||
const CAmount nValue;
|
||||
const int nHeight;
|
||||
@@ -101,17 +100,17 @@ public:
|
||||
*/
|
||||
CClaimScriptUndoAddOp(const COutPoint& point, int nHeight);
|
||||
/**
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -142,17 +141,17 @@ public:
|
||||
*/
|
||||
CClaimScriptSpendOp(const COutPoint& point, int nHeight, int& nValidHeight);
|
||||
/**
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -168,7 +167,6 @@ protected:
|
||||
const COutPoint point;
|
||||
const int nHeight;
|
||||
int& nValidHeight;
|
||||
int nOriginalHeight;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -184,19 +182,19 @@ public:
|
||||
* @param[in] nHeight entry height of the claim
|
||||
* @param[in] nValidHeight valid height of the claim
|
||||
*/
|
||||
CClaimScriptUndoSpendOp(const COutPoint& point, CAmount nValue, int nHeight, int nValidHeight, int nOriginalHeight);
|
||||
CClaimScriptUndoSpendOp(const COutPoint& point, CAmount nValue, int nHeight, int nValidHeight);
|
||||
/**
|
||||
* Implementation of OP_CLAIM_NAME handler
|
||||
* Implamention of OP_CLAIM_NAME handler
|
||||
* @see CClaimScriptOp::claimName
|
||||
*/
|
||||
bool claimName(CClaimTrieCache& trieCache, const std::string& name) override;
|
||||
/**
|
||||
* Implementation of OP_UPDATE_CLAIM handler
|
||||
* Implamention of OP_UPDATE_CLAIM handler
|
||||
* @see CClaimScriptOp::updateClaim
|
||||
*/
|
||||
bool updateClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
/**
|
||||
* Implementation of OP_SUPPORT_CLAIM handler
|
||||
* Implamention of OP_SUPPORT_CLAIM handler
|
||||
* @see CClaimScriptOp::supportClaim
|
||||
*/
|
||||
bool supportClaim(CClaimTrieCache& trieCache, const std::string& name, const uint160& claimId) override;
|
||||
@@ -213,7 +211,6 @@ protected:
|
||||
const CAmount nValue;
|
||||
const int nHeight;
|
||||
const int nValidHeight;
|
||||
const int nOriginalHeight;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -224,24 +221,30 @@ protected:
|
||||
*/
|
||||
bool ProcessClaim(CClaimScriptOp& claimOp, CClaimTrieCache& trieCache, const CScript& scriptPubKey);
|
||||
|
||||
struct spentClaimType { std::string name; uint160 id; int originalHeight; };
|
||||
typedef std::vector<spentClaimType> spentClaimsType;
|
||||
typedef std::pair<std::string, uint160> spentClaimType;
|
||||
|
||||
struct CUpdateCacheCallbacks
|
||||
{
|
||||
std::function<CScript(const COutPoint& point)> findScriptKey;
|
||||
std::function<void(uint32_t, uint32_t, uint32_t)> claimUndoHeights;
|
||||
};
|
||||
typedef std::vector<spentClaimType> spentClaimsType;
|
||||
|
||||
/**
|
||||
* Function to spend claim from tie, keeping the successful list on
|
||||
* @param[in] tx transaction inputs/outputs
|
||||
* @param[in] trieCache trie to operate on
|
||||
* @param[in] view coins cache
|
||||
* @param[in] scriptPubKey claim script to be decoded
|
||||
* @param[in] point pair of transaction hash and its index
|
||||
* @param[in] nHeight entry height of the claim
|
||||
* @param[out] fallback optional callbacks
|
||||
* @param[out] nValidHeight valid height of the claim
|
||||
* @param[out] spentClaims inserts successfully spent claim
|
||||
*/
|
||||
void UpdateCache(const CTransaction& tx, CClaimTrieCache& trieCache, const CCoinsViewCache& view, int nHeight, const CUpdateCacheCallbacks& callbacks = {});
|
||||
bool SpendClaim(CClaimTrieCache& trieCache, const CScript& scriptPubKey, const COutPoint& point, int nHeight, int& nValidHeight, spentClaimsType& spentClaims);
|
||||
|
||||
/**
|
||||
* Function to add / update (that present in spent list) claim in trie
|
||||
* @param[in] trieCache trie to operate on
|
||||
* @param[in] scriptPubKey claim script to be decoded
|
||||
* @param[in] point pair of transaction hash and its index
|
||||
* @param[in] nValue ` value of the claim
|
||||
* @param[in] nHeight entry height of the claim
|
||||
* @param[out] spentClaims erases successfully added claim
|
||||
*/
|
||||
bool AddSpendClaim(CClaimTrieCache& trieCache, const CScript& scriptPubKey, const COutPoint& point, CAmount nValue, int nHeight, spentClaimsType& spentClaims);
|
||||
|
||||
#endif // CLAIMSCRIPTOP_H
|
||||
+2532
File diff suppressed because it is too large.
Load diff
+826
@@ -0,0 +1,826 @@
|
||||
#ifndef BITCOIN_CLAIMTRIE_H
|
||||
#define BITCOIN_CLAIMTRIE_H
|
||||
|
||||
#include <amount.h>
|
||||
#include <serialize.h>
|
||||
#include <uint256.h>
|
||||
#include <util.h>
|
||||
#include <dbwrapper.h>
|
||||
#include <chainparams.h>
|
||||
#include <primitives/transaction.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
// leveldb keys
|
||||
#define HASH_BLOCK 'h'
|
||||
#define CURRENT_HEIGHT 't'
|
||||
#define TRIE_NODE 'n'
|
||||
#define CLAIM_BY_ID 'i'
|
||||
#define CLAIM_QUEUE_ROW 'r'
|
||||
#define CLAIM_QUEUE_NAME_ROW 'm'
|
||||
#define EXP_QUEUE_ROW 'e'
|
||||
#define SUPPORT 's'
|
||||
#define SUPPORT_QUEUE_ROW 'u'
|
||||
#define SUPPORT_QUEUE_NAME_ROW 'p'
|
||||
#define SUPPORT_EXP_QUEUE_ROW 'x'
|
||||
|
||||
uint256 getValueHash(COutPoint outPoint, int nHeightOfLastTakeover);
|
||||
|
||||
class CClaimValue
|
||||
{
|
||||
public:
|
||||
COutPoint outPoint;
|
||||
uint160 claimId;
|
||||
CAmount nAmount;
|
||||
CAmount nEffectiveAmount;
|
||||
int nHeight;
|
||||
int nValidAtHeight;
|
||||
|
||||
CClaimValue() {};
|
||||
|
||||
CClaimValue(COutPoint outPoint, uint160 claimId, CAmount nAmount, int nHeight,
|
||||
int nValidAtHeight)
|
||||
: outPoint(outPoint), claimId(claimId)
|
||||
, nAmount(nAmount), nEffectiveAmount(nAmount)
|
||||
, nHeight(nHeight), nValidAtHeight(nValidAtHeight)
|
||||
{}
|
||||
|
||||
CClaimValue(CClaimValue&&) = default;
|
||||
CClaimValue(const CClaimValue&) = default;
|
||||
CClaimValue& operator=(CClaimValue&&) = default;
|
||||
CClaimValue& operator=(const CClaimValue&) = default;
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action) {
|
||||
READWRITE(outPoint);
|
||||
READWRITE(claimId);
|
||||
READWRITE(nAmount);
|
||||
READWRITE(nHeight);
|
||||
READWRITE(nValidAtHeight);
|
||||
}
|
||||
|
||||
bool operator<(const CClaimValue& other) const
|
||||
{
|
||||
if (nEffectiveAmount < other.nEffectiveAmount)
|
||||
return true;
|
||||
else if (nEffectiveAmount == other.nEffectiveAmount)
|
||||
{
|
||||
if (nHeight > other.nHeight)
|
||||
return true;
|
||||
else if (nHeight == other.nHeight)
|
||||
{
|
||||
if (outPoint != other.outPoint && !(outPoint < other.outPoint))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool operator==(const CClaimValue& other) const
|
||||
{
|
||||
return outPoint == other.outPoint && claimId == other.claimId && nAmount == other.nAmount && nHeight == other.nHeight && nValidAtHeight == other.nValidAtHeight;
|
||||
}
|
||||
|
||||
bool operator!=(const CClaimValue& other) const
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
};
|
||||
|
||||
class CSupportValue
|
||||
{
|
||||
public:
|
||||
COutPoint outPoint;
|
||||
uint160 supportedClaimId;
|
||||
CAmount nAmount;
|
||||
int nHeight;
|
||||
int nValidAtHeight;
|
||||
|
||||
CSupportValue() {};
|
||||
CSupportValue(COutPoint outPoint, uint160 supportedClaimId,
|
||||
CAmount nAmount, int nHeight, int nValidAtHeight)
|
||||
: outPoint(outPoint), supportedClaimId(supportedClaimId)
|
||||
, nAmount(nAmount), nHeight(nHeight)
|
||||
, nValidAtHeight(nValidAtHeight)
|
||||
{}
|
||||
|
||||
CSupportValue(CSupportValue&&) = default;
|
||||
CSupportValue(const CSupportValue&) = default;
|
||||
CSupportValue& operator=(CSupportValue&&) = default;
|
||||
CSupportValue& operator=(const CSupportValue&) = default;
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action) {
|
||||
READWRITE(outPoint);
|
||||
READWRITE(supportedClaimId);
|
||||
READWRITE(nAmount);
|
||||
READWRITE(nHeight);
|
||||
READWRITE(nValidAtHeight);
|
||||
}
|
||||
|
||||
bool operator==(const CSupportValue& other) const
|
||||
{
|
||||
return outPoint == other.outPoint && supportedClaimId == other.supportedClaimId && nAmount == other.nAmount && nHeight == other.nHeight && nValidAtHeight == other.nValidAtHeight;
|
||||
}
|
||||
|
||||
bool operator!=(const CSupportValue& other) const
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
};
|
||||
|
||||
class CClaimTrieNode;
|
||||
class CClaimTrie;
|
||||
|
||||
typedef std::vector<CSupportValue> supportMapEntryType;
|
||||
typedef std::map<unsigned char, CClaimTrieNode*> nodeMapType;
|
||||
|
||||
class CClaimTrieNode
|
||||
{
|
||||
public:
|
||||
CClaimTrieNode() : nHeightOfLastTakeover(0) {}
|
||||
CClaimTrieNode(uint256 hash) : hash(hash), nHeightOfLastTakeover(0) {}
|
||||
CClaimTrieNode(const CClaimTrieNode&) = default;
|
||||
CClaimTrieNode(CClaimTrieNode&& other)
|
||||
{
|
||||
hash = std::move(other.hash);
|
||||
claims = std::move(other.claims);
|
||||
children = std::move(other.children);
|
||||
nHeightOfLastTakeover = other.nHeightOfLastTakeover;
|
||||
}
|
||||
|
||||
CClaimTrieNode& operator=(const CClaimTrieNode&) = default;
|
||||
CClaimTrieNode& operator=(CClaimTrieNode&& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
hash = std::move(other.hash);
|
||||
claims = std::move(other.claims);
|
||||
children = std::move(other.children);
|
||||
nHeightOfLastTakeover = other.nHeightOfLastTakeover;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
uint256 hash;
|
||||
nodeMapType children;
|
||||
int nHeightOfLastTakeover;
|
||||
std::vector<CClaimValue> claims;
|
||||
|
||||
bool insertClaim(CClaimValue claim);
|
||||
bool removeClaim(const COutPoint& outPoint, CClaimValue& claim);
|
||||
bool getBestClaim(CClaimValue& claim) const;
|
||||
bool empty() const {return children.empty() && claims.empty();}
|
||||
bool haveClaim(const COutPoint& outPoint) const;
|
||||
void reorderClaims(supportMapEntryType& supports);
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action) {
|
||||
READWRITE(hash);
|
||||
READWRITE(claims);
|
||||
READWRITE(nHeightOfLastTakeover);
|
||||
}
|
||||
|
||||
bool operator==(const CClaimTrieNode& other) const
|
||||
{
|
||||
return hash == other.hash && claims == other.claims;
|
||||
}
|
||||
|
||||
bool operator!=(const CClaimTrieNode& other) const
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
};
|
||||
|
||||
struct nodenamecompare
|
||||
{
|
||||
bool operator() (const std::string& i, const std::string& j) const
|
||||
{
|
||||
if (i.size() == j.size())
|
||||
return i < j;
|
||||
return i.size() < j.size();
|
||||
}
|
||||
};
|
||||
|
||||
struct outPointHeightType
|
||||
{
|
||||
COutPoint outPoint;
|
||||
int nHeight;
|
||||
|
||||
outPointHeightType() {}
|
||||
|
||||
outPointHeightType(COutPoint outPoint, int nHeight)
|
||||
: outPoint(outPoint), nHeight(nHeight) {}
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action)
|
||||
{
|
||||
READWRITE(outPoint);
|
||||
READWRITE(nHeight);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
struct nameOutPointHeightType
|
||||
{
|
||||
std::string name;
|
||||
COutPoint outPoint;
|
||||
int nHeight;
|
||||
|
||||
nameOutPointHeightType() {}
|
||||
|
||||
nameOutPointHeightType(std::string name, COutPoint outPoint, int nHeight)
|
||||
: name(std::move(name)), outPoint(outPoint), nHeight(nHeight) {}
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action)
|
||||
{
|
||||
READWRITE(name);
|
||||
READWRITE(outPoint);
|
||||
READWRITE(nHeight);
|
||||
}
|
||||
};
|
||||
|
||||
struct nameOutPointType
|
||||
{
|
||||
std::string name;
|
||||
COutPoint outPoint;
|
||||
|
||||
nameOutPointType() {}
|
||||
|
||||
nameOutPointType(std::string name, COutPoint outPoint)
|
||||
: name(std::move(name)), outPoint(outPoint) {}
|
||||
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action)
|
||||
{
|
||||
READWRITE(name);
|
||||
READWRITE(outPoint);
|
||||
}
|
||||
};
|
||||
|
||||
class CClaimIndexElement
|
||||
{
|
||||
public:
|
||||
ADD_SERIALIZE_METHODS;
|
||||
|
||||
template <typename Stream, typename Operation>
|
||||
inline void SerializationOp(Stream& s, Operation ser_action) {
|
||||
READWRITE(name);
|
||||
READWRITE(claim);
|
||||
}
|
||||
|
||||
std::string name;
|
||||
CClaimValue claim;
|
||||
};
|
||||
|
||||
typedef std::pair<std::string, CClaimValue> claimQueueEntryType;
|
||||
|
||||
typedef std::pair<std::string, CSupportValue> supportQueueEntryType;
|
||||
|
||||
typedef std::map<std::string, supportMapEntryType> supportMapType;
|
||||
|
||||
typedef std::vector<outPointHeightType> queueNameRowType;
|
||||
typedef std::map<std::string, queueNameRowType> queueNameType;
|
||||
|
||||
typedef std::vector<nameOutPointHeightType> insertUndoType;
|
||||
|
||||
typedef std::vector<nameOutPointType> expirationQueueRowType;
|
||||
typedef std::map<int, expirationQueueRowType> expirationQueueType;
|
||||
|
||||
typedef std::vector<claimQueueEntryType> claimQueueRowType;
|
||||
typedef std::map<int, claimQueueRowType> claimQueueType;
|
||||
|
||||
typedef std::vector<supportQueueEntryType> supportQueueRowType;
|
||||
typedef std::map<int, supportQueueRowType> supportQueueType;
|
||||
|
||||
typedef std::map<std::string, CClaimTrieNode*, nodenamecompare> nodeCacheType;
|
||||
|
||||
typedef std::map<std::string, uint256> hashMapType;
|
||||
|
||||
typedef std::set<CClaimValue> claimIndexClaimListType;
|
||||
typedef std::vector<CClaimIndexElement> claimIndexElementListType;
|
||||
|
||||
struct claimsForNameType
|
||||
{
|
||||
std::vector<CClaimValue> claims;
|
||||
std::vector<CSupportValue> supports;
|
||||
int nLastTakeoverHeight;
|
||||
std::string name;
|
||||
|
||||
claimsForNameType(std::vector<CClaimValue> claims, std::vector<CSupportValue> supports,
|
||||
int nLastTakeoverHeight, const std::string& name)
|
||||
: claims(std::move(claims)), supports(std::move(supports)),
|
||||
nLastTakeoverHeight(nLastTakeoverHeight), name(name) {}
|
||||
|
||||
claimsForNameType(const claimsForNameType&) = default;
|
||||
claimsForNameType(claimsForNameType&& other)
|
||||
{
|
||||
claims = std::move(other.claims);
|
||||
supports = std::move(other.supports);
|
||||
name = std::move(other.name);
|
||||
nLastTakeoverHeight = other.nLastTakeoverHeight;
|
||||
}
|
||||
|
||||
claimsForNameType& operator=(const claimsForNameType&) = default;
|
||||
claimsForNameType& operator=(claimsForNameType&& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
claims = std::move(other.claims);
|
||||
supports = std::move(other.supports);
|
||||
name = std::move(other.name);
|
||||
nLastTakeoverHeight = other.nLastTakeoverHeight;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
virtual ~claimsForNameType() {}
|
||||
};
|
||||
|
||||
class CClaimTrieCacheBase;
|
||||
class CClaimTrieCacheExpirationFork;
|
||||
|
||||
class CClaimTrie
|
||||
{
|
||||
public:
|
||||
CClaimTrie(bool fMemory = false, bool fWipe = false, int nProportionalDelayFactor = 32)
|
||||
: db(GetDataDir() / "claimtrie", 20 * 1024 * 1024, fMemory, fWipe, false)
|
||||
, nCurrentHeight(0), nExpirationTime(Params().GetConsensus().nOriginalClaimExpirationTime)
|
||||
, nProportionalDelayFactor(nProportionalDelayFactor)
|
||||
, root(uint256S("0000000000000000000000000000000000000000000000000000000000000001"))
|
||||
{}
|
||||
|
||||
uint256 getMerkleHash();
|
||||
|
||||
bool empty() const;
|
||||
void clear();
|
||||
|
||||
bool checkConsistency() const;
|
||||
|
||||
bool WriteToDisk();
|
||||
bool ReadFromDisk(bool check = false);
|
||||
|
||||
bool getInfoForName(const std::string& name, CClaimValue& claim) const;
|
||||
bool getLastTakeoverForName(const std::string& name, int& lastTakeoverHeight) const;
|
||||
|
||||
std::vector<CClaimValue> getClaimsForName(const std::string& name) const;
|
||||
|
||||
bool queueEmpty() const;
|
||||
bool supportEmpty() const;
|
||||
bool supportQueueEmpty() const;
|
||||
bool expirationQueueEmpty() const;
|
||||
|
||||
void setExpirationTime(int t);
|
||||
|
||||
void addToClaimIndex(const std::string& name, const CClaimValue& claim);
|
||||
void removeFromClaimIndex(const CClaimValue& claim);
|
||||
|
||||
bool getClaimById(const uint160 claimId, std::string& name, CClaimValue& claim) const;
|
||||
|
||||
bool haveClaim(const std::string& name, const COutPoint& outPoint) const;
|
||||
bool haveClaimInQueue(const std::string& name, const COutPoint& outPoint,
|
||||
int& nValidAtHeight) const;
|
||||
|
||||
bool haveSupport(const std::string& name, const COutPoint& outPoint) const;
|
||||
bool haveSupportInQueue(const std::string& name, const COutPoint& outPoint,
|
||||
int& nValidAtHeight) const;
|
||||
|
||||
unsigned int getTotalNamesInTrie() const;
|
||||
unsigned int getTotalClaimsInTrie() const;
|
||||
CAmount getTotalValueOfClaimsInTrie(bool fControllingOnly) const;
|
||||
|
||||
friend class CClaimTrieCacheBase;
|
||||
friend class CClaimTrieCacheExpirationFork;
|
||||
|
||||
CDBWrapper db;
|
||||
int nCurrentHeight;
|
||||
int nExpirationTime;
|
||||
int nProportionalDelayFactor;
|
||||
|
||||
private:
|
||||
void clear(CClaimTrieNode* current);
|
||||
|
||||
const CClaimTrieNode* getNodeForName(const std::string& name) const;
|
||||
|
||||
bool update(nodeCacheType& cache, hashMapType& hashes,
|
||||
std::map<std::string, int>& takeoverHeights,
|
||||
const uint256& hashBlock, claimQueueType& queueCache,
|
||||
queueNameType& queueNameCache,
|
||||
expirationQueueType& expirationQueueCache, int nNewHeight,
|
||||
supportMapType& supportCache,
|
||||
supportQueueType& supportQueueCache,
|
||||
queueNameType& supportQueueNameCache,
|
||||
expirationQueueType& supportExpirationQueueCache);
|
||||
bool updateName(const std::string& name, CClaimTrieNode* updatedNode);
|
||||
bool updateHash(const std::string& name, uint256& hash);
|
||||
bool updateTakeoverHeight(const std::string& name, int nTakeoverHeight);
|
||||
bool recursiveNullify(CClaimTrieNode* node, const std::string& name);
|
||||
|
||||
bool recursiveCheckConsistency(const CClaimTrieNode* node) const;
|
||||
|
||||
bool InsertFromDisk(const std::string& name, CClaimTrieNode* node);
|
||||
|
||||
unsigned int getTotalNamesRecursive(const CClaimTrieNode* current) const;
|
||||
unsigned int getTotalClaimsRecursive(const CClaimTrieNode* current) const;
|
||||
CAmount getTotalValueOfClaimsRecursive(const CClaimTrieNode* current,
|
||||
bool fControllingOnly) const;
|
||||
|
||||
bool getQueueRow(int nHeight, claimQueueRowType& row) const;
|
||||
bool getQueueNameRow(const std::string& name, queueNameRowType& row) const;
|
||||
bool getExpirationQueueRow(int nHeight, expirationQueueRowType& row) const;
|
||||
bool getSupportNode(std::string name, supportMapEntryType& node) const;
|
||||
bool getSupportQueueRow(int nHeight, supportQueueRowType& row) const;
|
||||
bool getSupportQueueNameRow(const std::string& name, queueNameRowType& row) const;
|
||||
bool getSupportExpirationQueueRow(int nHeight, expirationQueueRowType& row) const;
|
||||
|
||||
void markNodeDirty(const std::string& name, CClaimTrieNode* node);
|
||||
void updateQueueRow(int nHeight, claimQueueRowType& row);
|
||||
void updateQueueNameRow(const std::string& name,
|
||||
queueNameRowType& row);
|
||||
void updateExpirationRow(int nHeight, expirationQueueRowType& row);
|
||||
void updateSupportMap(const std::string& name, supportMapEntryType& node);
|
||||
void updateSupportQueue(int nHeight, supportQueueRowType& row);
|
||||
void updateSupportNameQueue(const std::string& name,
|
||||
queueNameRowType& row);
|
||||
void updateSupportExpirationQueue(int nHeight, expirationQueueRowType& row);
|
||||
|
||||
void BatchWriteNode(CDBBatch& batch, const std::string& name,
|
||||
const CClaimTrieNode* pNode) const;
|
||||
void BatchWriteQueueRows(CDBBatch& batch);
|
||||
void BatchWriteQueueNameRows(CDBBatch& batch);
|
||||
void BatchWriteExpirationQueueRows(CDBBatch& batch);
|
||||
void BatchWriteSupportNodes(CDBBatch& batch);
|
||||
void BatchWriteSupportQueueRows(CDBBatch& batch);
|
||||
void BatchWriteSupportQueueNameRows(CDBBatch& batch);
|
||||
void BatchWriteSupportExpirationQueueRows(CDBBatch& batch);
|
||||
template<typename K> bool keyTypeEmpty(char key, K& dummy) const;
|
||||
|
||||
CClaimTrieNode root;
|
||||
uint256 hashBlock;
|
||||
|
||||
claimQueueType dirtyQueueRows;
|
||||
queueNameType dirtyQueueNameRows;
|
||||
expirationQueueType dirtyExpirationQueueRows;
|
||||
|
||||
supportQueueType dirtySupportQueueRows;
|
||||
queueNameType dirtySupportQueueNameRows;
|
||||
expirationQueueType dirtySupportExpirationQueueRows;
|
||||
|
||||
nodeCacheType dirtyNodes;
|
||||
supportMapType dirtySupportNodes;
|
||||
};
|
||||
|
||||
class CClaimTrieProofNode
|
||||
{
|
||||
public:
|
||||
CClaimTrieProofNode() {};
|
||||
CClaimTrieProofNode(std::vector<std::pair<unsigned char, uint256> > children,
|
||||
bool hasValue, uint256 valHash)
|
||||
: children(std::move(children)), hasValue(hasValue), valHash(std::move(valHash))
|
||||
{};
|
||||
CClaimTrieProofNode(const CClaimTrieProofNode&) = default;
|
||||
CClaimTrieProofNode(CClaimTrieProofNode&& other)
|
||||
{
|
||||
hasValue = other.hasValue;
|
||||
valHash = std::move(other.valHash);
|
||||
children = std::move(other.children);
|
||||
}
|
||||
CClaimTrieProofNode& operator=(const CClaimTrieProofNode&) = default;
|
||||
CClaimTrieProofNode& operator=(CClaimTrieProofNode&& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
hasValue = other.hasValue;
|
||||
valHash = std::move(other.valHash);
|
||||
children = std::move(other.children);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::vector<std::pair<unsigned char, uint256> > children;
|
||||
bool hasValue;
|
||||
uint256 valHash;
|
||||
};
|
||||
|
||||
class CClaimTrieProof
|
||||
{
|
||||
public:
|
||||
CClaimTrieProof() {};
|
||||
CClaimTrieProof(std::vector<CClaimTrieProofNode> nodes, bool hasValue, COutPoint outPoint, int nHeightOfLastTakeover) : nodes(std::move(nodes)), hasValue(hasValue), outPoint(outPoint), nHeightOfLastTakeover(nHeightOfLastTakeover) {}
|
||||
CClaimTrieProof(const CClaimTrieProof&) = default;
|
||||
CClaimTrieProof(CClaimTrieProof&& other)
|
||||
{
|
||||
hasValue = other.hasValue;
|
||||
outPoint = std::move(other.outPoint);
|
||||
nodes = std::move(other.nodes);
|
||||
nHeightOfLastTakeover = other.nHeightOfLastTakeover;
|
||||
}
|
||||
|
||||
CClaimTrieProof& operator=(const CClaimTrieProof&) = default;
|
||||
CClaimTrieProof& operator=(CClaimTrieProof&& other)
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
hasValue = other.hasValue;
|
||||
outPoint = std::move(other.outPoint);
|
||||
nodes = std::move(other.nodes);
|
||||
nHeightOfLastTakeover = other.nHeightOfLastTakeover;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::vector<CClaimTrieProofNode> nodes;
|
||||
bool hasValue;
|
||||
COutPoint outPoint;
|
||||
int nHeightOfLastTakeover;
|
||||
};
|
||||
|
||||
struct CNodeCallback {
|
||||
struct CRecursionInterruptionException : public std::exception {
|
||||
const bool success;
|
||||
explicit CRecursionInterruptionException(bool success) : success(success) {}
|
||||
};
|
||||
|
||||
virtual ~CNodeCallback()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback to be called on every trie node
|
||||
* @param[in] name full name of the node
|
||||
* @param[in] node pointer to node itself
|
||||
*
|
||||
* To breakout early throw an exception.
|
||||
* Throwing CRecursionInterruptionException will allow you to set the return value of iterateTrie.
|
||||
*/
|
||||
virtual void visit(const std::string& name, const CClaimTrieNode* node) = 0;
|
||||
};
|
||||
|
||||
class CClaimTrieCacheBase
|
||||
{
|
||||
public:
|
||||
CClaimTrieCacheBase(CClaimTrie* base, bool fRequireTakeoverHeights = true)
|
||||
: base(base), fRequireTakeoverHeights(fRequireTakeoverHeights)
|
||||
{
|
||||
assert(base);
|
||||
nCurrentHeight = base->nCurrentHeight;
|
||||
}
|
||||
|
||||
uint256 getMerkleHash(bool forceCompute = false) const;
|
||||
|
||||
bool empty() const;
|
||||
bool flush();
|
||||
bool dirty() const { return !dirtyHashes.empty(); }
|
||||
|
||||
CClaimTrieNode* getRoot() const
|
||||
{
|
||||
const auto iter = cache.find("");
|
||||
return iter == cache.end() ? &(base->root) : iter->second;
|
||||
}
|
||||
|
||||
bool addClaim(const std::string& name, const COutPoint& outPoint,
|
||||
uint160 claimId, CAmount nAmount, int nHeight) const;
|
||||
bool undoAddClaim(const std::string& name, const COutPoint& outPoint, int nHeight) const;
|
||||
bool spendClaim(const std::string& name, const COutPoint& outPoint, int nHeight, int& nValidAtHeight) const;
|
||||
bool undoSpendClaim(const std::string& name, const COutPoint& outPoint,
|
||||
uint160 claimId, CAmount nAmount, int nHeight,
|
||||
int nValidAtHeight) const;
|
||||
|
||||
bool addSupport(const std::string& name, const COutPoint& outPoint,
|
||||
CAmount nAmount, uint160 supportedClaimId,
|
||||
int nHeight) const;
|
||||
bool undoAddSupport(const std::string& name, const COutPoint& outPoint,
|
||||
int nHeight) const;
|
||||
bool spendSupport(const std::string& name, const COutPoint& outPoint,
|
||||
int nHeight, int& nValidAtHeight) const;
|
||||
bool undoSpendSupport(const std::string& name, const COutPoint& outPoint,
|
||||
uint160 supportedClaimId, CAmount nAmount,
|
||||
int nHeight, int nValidAtHeight) const;
|
||||
|
||||
uint256 getBestBlock();
|
||||
void setBestBlock(const uint256& hashBlock);
|
||||
|
||||
virtual bool incrementBlock(insertUndoType& insertUndo,
|
||||
claimQueueRowType& expireUndo,
|
||||
insertUndoType& insertSupportUndo,
|
||||
supportQueueRowType& expireSupportUndo,
|
||||
std::vector<std::pair<std::string, int> >& takeoverHeightUndo);
|
||||
virtual bool decrementBlock(insertUndoType& insertUndo,
|
||||
claimQueueRowType& expireUndo,
|
||||
insertUndoType& insertSupportUndo,
|
||||
supportQueueRowType& expireSupportUndo,
|
||||
std::vector<std::pair<std::string, int> >& takeoverHeightUndo);
|
||||
|
||||
virtual ~CClaimTrieCacheBase() { clear(); }
|
||||
|
||||
virtual bool getProofForName(const std::string& name, CClaimTrieProof& proof) const;
|
||||
virtual bool getInfoForName(const std::string& name, CClaimValue& claim) const;
|
||||
|
||||
bool finalizeDecrement() const;
|
||||
|
||||
bool iterateTrie(CNodeCallback& callback) const;
|
||||
|
||||
virtual claimsForNameType getClaimsForName(const std::string& name) const;
|
||||
|
||||
CAmount getEffectiveAmountForClaim(const std::string& name, const uint160& claimId,
|
||||
std::vector<CSupportValue>* supports = nullptr) const;
|
||||
CAmount getEffectiveAmountForClaim(const claimsForNameType& claims, const uint160& claimId,
|
||||
std::vector<CSupportValue>* supports = nullptr) const;
|
||||
|
||||
protected:
|
||||
// Should be private: Do not use unless you know what you're doing.
|
||||
CClaimTrieNode* addNodeToCache(const std::string& position, CClaimTrieNode* original) const;
|
||||
bool recursiveComputeMerkleHash(CClaimTrieNode* tnCurrent,
|
||||
const std::string& sPos,
|
||||
bool forceCompute = false) const;
|
||||
bool recursivePruneName(CClaimTrieNode* tnCurrent, unsigned int nPos, const std::string& sName, bool* pfNullified = nullptr) const;
|
||||
void checkNamesForTakeover(insertUndoType& insertUndo, insertUndoType& insertSupportUndo,
|
||||
std::vector<std::pair<std::string, int> >& takeoverHeightUndo) const;
|
||||
|
||||
virtual bool insertClaimIntoTrie(const std::string& name, CClaimValue claim,
|
||||
bool fCheckTakeover = false) const;
|
||||
virtual bool removeClaimFromTrie(const std::string& name, const COutPoint& outPoint,
|
||||
CClaimValue& claim,
|
||||
bool fCheckTakeover = false) const;
|
||||
|
||||
virtual bool insertSupportIntoMap(const std::string& name,
|
||||
CSupportValue support,
|
||||
bool fCheckTakeover) const;
|
||||
virtual bool removeSupportFromMap(const std::string& name, const COutPoint& outPoint,
|
||||
CSupportValue& support,
|
||||
bool fCheckTakeover) const;
|
||||
|
||||
virtual void addClaimToQueues(const std::string& name, CClaimValue& claim) const;
|
||||
virtual bool addSupportToQueues(const std::string& name, CSupportValue& support) const;
|
||||
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
|
||||
|
||||
void addToExpirationQueue(int nExpirationHeight, nameOutPointType& entry) const;
|
||||
void removeFromExpirationQueue(const std::string& name, const COutPoint& outPoint,
|
||||
int nHeight) const;
|
||||
|
||||
void addSupportToExpirationQueue(int nExpirationHeight,
|
||||
nameOutPointType& entry) const;
|
||||
void removeSupportFromExpirationQueue(const std::string& name,
|
||||
const COutPoint& outPoint,
|
||||
int nHeight) const;
|
||||
|
||||
bool getSupportsForName(const std::string& name,
|
||||
supportMapEntryType& supports) const;
|
||||
|
||||
virtual int getDelayForName(const std::string& name, const uint160& claimId) const;
|
||||
|
||||
mutable nodeCacheType cache;
|
||||
CClaimTrie* base;
|
||||
mutable int nCurrentHeight; // Height of the block that is being worked on, which is
|
||||
// one greater than the height of the chain's tip
|
||||
|
||||
private:
|
||||
|
||||
bool fRequireTakeoverHeights;
|
||||
|
||||
mutable nodeCacheType block_originals;
|
||||
mutable std::set<std::string> dirtyHashes;
|
||||
mutable hashMapType cacheHashes;
|
||||
mutable claimQueueType claimQueueCache;
|
||||
mutable queueNameType claimQueueNameCache;
|
||||
mutable expirationQueueType expirationQueueCache;
|
||||
mutable supportMapType supportCache;
|
||||
mutable supportQueueType supportQueueCache;
|
||||
mutable queueNameType supportQueueNameCache;
|
||||
mutable expirationQueueType supportExpirationQueueCache;
|
||||
mutable std::set<std::string> namesToCheckForTakeover;
|
||||
mutable std::map<std::string, int> cacheTakeoverHeights;
|
||||
mutable claimIndexElementListType claimsToAdd;
|
||||
mutable claimIndexClaimListType claimsToDelete;
|
||||
|
||||
uint256 hashBlock;
|
||||
|
||||
bool reorderTrieNode(const std::string& name, bool fCheckTakeover) const;
|
||||
|
||||
bool clear() const;
|
||||
|
||||
// generally the opposite of addClaimToQueues, but they aren't perfectly symmetrical:
|
||||
bool removeClaim(const std::string& name, const COutPoint& outPoint, int nHeight, int& nValidAtHeight, bool fCheckTakeover) const;
|
||||
bool removeClaimFromQueue(const std::string& name, const COutPoint& outPoint,
|
||||
CClaimValue& claim) const;
|
||||
|
||||
claimQueueType::iterator getQueueCacheRow(int nHeight,
|
||||
bool createIfNotExists) const;
|
||||
queueNameType::iterator getQueueCacheNameRow(const std::string& name,
|
||||
bool createIfNotExists) const;
|
||||
expirationQueueType::iterator getExpirationQueueCacheRow(int nHeight,
|
||||
bool createIfNotExists) const;
|
||||
|
||||
bool removeSupport(const std::string& name, const COutPoint& outPoint,
|
||||
int nHeight, int& nValidAtHeight,
|
||||
bool fCheckTakeover) const;
|
||||
|
||||
supportQueueType::iterator getSupportQueueCacheRow(int nHeight,
|
||||
bool createIfNotExists) const;
|
||||
queueNameType::iterator getSupportQueueCacheNameRow(const std::string& name,
|
||||
bool createIfNotExists) const;
|
||||
expirationQueueType::iterator getSupportExpirationQueueCacheRow(int nHeight,
|
||||
bool createIfNotExists) const;
|
||||
|
||||
bool removeSupportFromQueue(const std::string& name, const COutPoint& outPoint,
|
||||
CSupportValue& support) const;
|
||||
|
||||
bool getLastTakeoverForName(const std::string& name, int& lastTakeoverHeight) const;
|
||||
|
||||
int getDelayForName(const std::string& name) const;
|
||||
|
||||
uint256 getLeafHashForProof(const std::string& currentPosition, const CClaimTrieNode* currentNode) const;
|
||||
|
||||
bool getOriginalInfoForName(const std::string& name, CClaimValue& claim) const;
|
||||
|
||||
int getNumBlocksOfContinuousOwnership(const std::string& name) const;
|
||||
|
||||
void recursiveIterateTrie(std::string& name, const CClaimTrieNode* current, CNodeCallback& callback) const;
|
||||
|
||||
const CClaimTrieNode* getNodeForName(const std::string& name) const;
|
||||
};
|
||||
|
||||
class CClaimTrieCacheExpirationFork: public CClaimTrieCacheBase {
|
||||
public:
|
||||
CClaimTrieCacheExpirationFork(CClaimTrie* base, bool fRequireTakeoverHeights = true)
|
||||
: CClaimTrieCacheBase(base, fRequireTakeoverHeights) {}
|
||||
|
||||
virtual ~CClaimTrieCacheExpirationFork() {}
|
||||
|
||||
bool forkForExpirationChange(bool increment) const;
|
||||
|
||||
// TODO: move the expiration fork code from main.cpp to overrides of increment/decrement block
|
||||
|
||||
private:
|
||||
void removeAndAddSupportToExpirationQueue(expirationQueueRowType &row, int height, bool increment) const;
|
||||
void removeAndAddToExpirationQueue(expirationQueueRowType &row, int height, bool increment) const;
|
||||
};
|
||||
|
||||
class CClaimTrieCacheNormalizationFork: public CClaimTrieCacheExpirationFork {
|
||||
public:
|
||||
CClaimTrieCacheNormalizationFork(CClaimTrie* base, bool fRequireTakeoverHeights = true)
|
||||
: CClaimTrieCacheExpirationFork(base, fRequireTakeoverHeights),
|
||||
overrideInsertNormalization(false), overrideRemoveNormalization(false) {}
|
||||
|
||||
virtual ~CClaimTrieCacheNormalizationFork() {}
|
||||
|
||||
bool shouldNormalize() const;
|
||||
|
||||
// lower-case and normalize any input string name
|
||||
// see: https://unicode.org/reports/tr15/#Norm_Forms
|
||||
std::string normalizeClaimName(const std::string& name, bool force = false) const; // public only for validating name field on update op
|
||||
|
||||
virtual bool incrementBlock(insertUndoType& insertUndo,
|
||||
claimQueueRowType& expireUndo,
|
||||
insertUndoType& insertSupportUndo,
|
||||
supportQueueRowType& expireSupportUndo,
|
||||
std::vector<std::pair<std::string, int> >& takeoverHeightUndo);
|
||||
virtual bool decrementBlock(insertUndoType& insertUndo,
|
||||
claimQueueRowType& expireUndo,
|
||||
insertUndoType& insertSupportUndo,
|
||||
supportQueueRowType& expireSupportUndo,
|
||||
std::vector<std::pair<std::string, int> >& takeoverHeightUndo);
|
||||
|
||||
virtual bool getProofForName(const std::string& name, CClaimTrieProof& proof) const;
|
||||
virtual bool getInfoForName(const std::string& name, CClaimValue& claim) const;
|
||||
virtual claimsForNameType getClaimsForName(const std::string& name) const;
|
||||
|
||||
protected:
|
||||
virtual bool insertClaimIntoTrie(const std::string& name, CClaimValue claim, bool fCheckTakeover = false) const;
|
||||
virtual bool removeClaimFromTrie(const std::string& name, const COutPoint& outPoint,
|
||||
CClaimValue& claim, bool fCheckTakeover = false) const;
|
||||
|
||||
virtual bool insertSupportIntoMap(const std::string& name, CSupportValue support, bool fCheckTakeover) const;
|
||||
virtual bool removeSupportFromMap(const std::string& name, const COutPoint& outPoint,
|
||||
CSupportValue& support, bool fCheckTakeover) const;
|
||||
virtual int getDelayForName(const std::string& name, const uint160& claimId) const;
|
||||
|
||||
virtual void addClaimToQueues(const std::string& name, CClaimValue& claim) const;
|
||||
virtual bool addSupportToQueues(const std::string& name, CSupportValue& support) const;
|
||||
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
|
||||
|
||||
private:
|
||||
bool overrideInsertNormalization, overrideRemoveNormalization;
|
||||
bool normalizeAllNamesInTrieIfNecessary(insertUndoType& insertUndo, claimQueueRowType& removeUndo,
|
||||
insertUndoType& insertSupportUndo, supportQueueRowType& expireSupportUndo,
|
||||
std::vector<std::pair<std::string, int> >& takeoverHeightUndo) const;
|
||||
};
|
||||
|
||||
typedef CClaimTrieCacheNormalizationFork CClaimTrieCache;
|
||||
|
||||
#endif // BITCOIN_CLAIMTRIE_H
|
||||
@@ -1,158 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
|
||||
project(libclaimtrie)
|
||||
set(CMAKE_CXX_STANDARD 14)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
include(../../contrib/cmake/cmake/CPM.cmake)
|
||||
include(ExternalProject)
|
||||
|
||||
set(CLAIMTRIE_SRC
|
||||
blob.cpp
|
||||
data.cpp
|
||||
forks.cpp
|
||||
hashes.cpp
|
||||
log.cpp
|
||||
trie.cpp
|
||||
txoutpoint.cpp
|
||||
uints.cpp
|
||||
./sqlite/sqlite3.c
|
||||
)
|
||||
|
||||
if(BIND)
|
||||
find_program(SWIG NAMES swig)
|
||||
string(TOLOWER ${BIND} BIND)
|
||||
if(${BIND} STREQUAL "python")
|
||||
find_package(PythonInterp 3.6 REQUIRED)
|
||||
find_package(PythonLibs 3.6 REQUIRED)
|
||||
set(BIND_INCLUDE_DIRS ${PYTHON_INCLUDE_DIRS})
|
||||
set(SWIG_OPTIONS -python;-py3)
|
||||
set(CMAKE_SHARED_LIBRARY_PREFIX _lib)
|
||||
elseif(${BIND} STREQUAL "go")
|
||||
find_program(GOLANG NAMES go)
|
||||
if(NOT GOLANG)
|
||||
message(FATAL_ERROR "Golang was not found in system path")
|
||||
endif()
|
||||
execute_process(COMMAND ${GOLANG} "version" OUTPUT_VARIABLE GOLANG_VERSION)
|
||||
STRING(REGEX MATCH "[0-9]+.[0-9]+.[0-9]" GOLANG_VERSION "${GOLANG_VERSION}")
|
||||
if(GOLANG_VERSION VERSION_LESS 1.5)
|
||||
message(FATAL_ERROR "Update Golang to at least 1.5, now " ${GOLANG_VERSION})
|
||||
endif()
|
||||
set(SWIG_OPTIONS -go;-cgo;-intgosize;32)
|
||||
set(POST_BUILD_COMMAND go)
|
||||
set(POST_BUILD_ARGS install;-x;${CMAKE_PROJECT_NAME}.go)
|
||||
# CGO_LDFLAGS is buggy so we should inject linker flags in generated go file
|
||||
set(POST_BUILD_PATCH -i "\"s/import \\\"C\\\"/\\/\\/ #cgo LDFLAGS: -L\\\$$\\{SRCDIR\\} -lclaimtrie\\nimport \\\"C\\\"/\"" ${CMAKE_PROJECT_NAME}.go)
|
||||
else()
|
||||
message(FATAL_ERROR "Implement a handler for ${BIND}")
|
||||
endif()
|
||||
add_custom_command(OUTPUT ${CMAKE_PROJECT_NAME}_wrap.cxx
|
||||
COMMAND ${SWIG}
|
||||
ARGS -c++ ${SWIG_OPTIONS} -outcurrentdir ${CMAKE_CURRENT_SOURCE_DIR}/${CMAKE_PROJECT_NAME}.i
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
set(CLAIMTRIE_SRC ${CLAIMTRIE_SRC}
|
||||
${CMAKE_PROJECT_NAME}_wrap.cxx
|
||||
)
|
||||
endif()
|
||||
|
||||
add_library(claimtrie SHARED ${CLAIMTRIE_SRC})
|
||||
if (POST_BUILD_PATCH)
|
||||
add_custom_command(TARGET claimtrie POST_BUILD
|
||||
COMMAND sed
|
||||
ARGS ${POST_BUILD_PATCH}
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
endif()
|
||||
if(POST_BUILD_COMMAND)
|
||||
add_custom_command(TARGET claimtrie POST_BUILD
|
||||
COMMAND ${POST_BUILD_COMMAND}
|
||||
ARGS ${POST_BUILD_ARGS}
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
endif()
|
||||
|
||||
target_include_directories(claimtrie PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
if(BIND_INCLUDE_DIRS)
|
||||
target_include_directories(claimtrie PRIVATE ${BIND_INCLUDE_DIRS})
|
||||
endif()
|
||||
|
||||
CPMAddPackage(
|
||||
NAME OpenSSL
|
||||
GITHUB_REPOSITORY openssl/openssl
|
||||
VERSION 1.0.2
|
||||
GIT_TAG OpenSSL_1_0_2r
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
if(OpenSSL_ADDED)
|
||||
string(TOLOWER ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR} ARCH)
|
||||
ExternalProject_Add(OpenSSL
|
||||
PREFIX openssl
|
||||
SOURCE_DIR ${OpenSSL_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${OpenSSL_SOURCE_DIR}/Configure ${ARCH} no-shared no-dso no-engines -fPIC --prefix=<INSTALL_DIR>
|
||||
BUILD_IN_SOURCE 1
|
||||
)
|
||||
add_dependencies(claimtrie OpenSSL)
|
||||
ExternalProject_Get_Property(OpenSSL INSTALL_DIR)
|
||||
target_link_directories(claimtrie PRIVATE ${INSTALL_DIR}/lib)
|
||||
target_include_directories(claimtrie PRIVATE ${INSTALL_DIR}/include)
|
||||
endif(OpenSSL_ADDED)
|
||||
|
||||
target_link_libraries(claimtrie PRIVATE ssl)
|
||||
|
||||
set(BOOST_LIBS filesystem,locale,system,chrono,thread,test)
|
||||
|
||||
set(BOOST_COMPONENTS filesystem;locale;system;chrono;thread;unit_test_framework)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME Boost
|
||||
GITHUB_REPOSITORY boostorg/boost
|
||||
VERSION 1.64.0
|
||||
COMPONENTS ${BOOST_COMPONENTS}
|
||||
GIT_TAG boost-1.69.0
|
||||
GIT_SUBMODULES libs/* tools/*
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
# if boost is found system wide we expect to be compiled against icu, so we can skip it
|
||||
if(Boost_ADDED)
|
||||
CPMAddPackage(
|
||||
NAME ICU
|
||||
GITHUB_REPOSITORY unicode-org/icu
|
||||
VERSION 63.2
|
||||
GIT_TAG release-63-2
|
||||
DOWNLOAD_ONLY TRUE
|
||||
)
|
||||
|
||||
if(ICU_ADDED)
|
||||
ExternalProject_Add(ICU
|
||||
PREFIX icu
|
||||
SOURCE_DIR ${ICU_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${ICU_SOURCE_DIR}/icu4c/source/configure --disable-extras --disable-strict --enable-static
|
||||
--disable-shared --disable-tests --disable-samples --disable-dyload --disable-layoutex CFLAGS=-fPIC CPPFLAGS=-fPIC --prefix=<INSTALL_DIR>
|
||||
)
|
||||
ExternalProject_Get_Property(ICU INSTALL_DIR)
|
||||
set(ICU_PATH ${INSTALL_DIR})
|
||||
target_link_directories(claimtrie PRIVATE ${ICU_PATH}/lib)
|
||||
target_include_directories(claimtrie PRIVATE ${ICU_PATH}/include)
|
||||
endif(ICU_ADDED)
|
||||
|
||||
ExternalProject_Add(Boost
|
||||
PREFIX boost
|
||||
DEPENDS ICU
|
||||
SOURCE_DIR ${Boost_SOURCE_DIR}
|
||||
CONFIGURE_COMMAND ${Boost_SOURCE_DIR}/bootstrap.sh --with-icu=${ICU_PATH} --with-libraries=${BOOST_LIBS} && ${Boost_SOURCE_DIR}/b2 headers
|
||||
BUILD_COMMAND ${Boost_SOURCE_DIR}/b2 install threading=multi -sNO_BZIP2=1 -sNO_ZLIB=1 link=static linkflags="-L${ICU_PATH}/lib -licuio -licuuc -licudata -licui18n" cxxflags=-fPIC boost.locale.iconv=off boost.locale.posix=off boost.locale.icu=on boost.locale.std=off -sICU_PATH=${ICU_PATH} --prefix=<INSTALL_DIR>
|
||||
INSTALL_COMMAND ""
|
||||
BUILD_IN_SOURCE 1
|
||||
)
|
||||
add_dependencies(claimtrie Boost)
|
||||
ExternalProject_Get_Property(Boost INSTALL_DIR)
|
||||
target_link_directories(claimtrie PRIVATE ${INSTALL_DIR}/lib)
|
||||
target_include_directories(claimtrie PRIVATE ${INSTALL_DIR}/include)
|
||||
set_property(DIRECTORY PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${Boost_SOURCE_DIR}/bin.v2)
|
||||
endif(Boost_ADDED)
|
||||
|
||||
target_link_libraries(claimtrie PRIVATE boost_filesystem boost_locale)
|
||||
@@ -1,172 +0,0 @@
|
||||
|
||||
#include <blob.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
/** Template base class for fixed-sized opaque blobs. */
|
||||
template<uint32_t BITS>
|
||||
CBaseBlob<BITS>::CBaseBlob()
|
||||
{
|
||||
SetNull();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
CBaseBlob<BITS>::CBaseBlob(const std::vector<uint8_t>& vec)
|
||||
{
|
||||
assert(vec.size() == size());
|
||||
std::copy(vec.begin(), vec.end(), begin());
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
CBaseBlob<BITS>::CBaseBlob(const CBaseBlob& o)
|
||||
{
|
||||
*this = o;
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
CBaseBlob<BITS>& CBaseBlob<BITS>::operator=(const CBaseBlob& o)
|
||||
{
|
||||
if (this != &o)
|
||||
std::copy(o.begin(), o.end(), begin());
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
int CBaseBlob<BITS>::Compare(const CBaseBlob& b) const
|
||||
{
|
||||
return std::memcmp(begin(), b.begin(), size());
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
bool CBaseBlob<BITS>::operator<(const CBaseBlob& b) const
|
||||
{
|
||||
return Compare(b) < 0;
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
bool CBaseBlob<BITS>::operator==(const CBaseBlob& b) const
|
||||
{
|
||||
return Compare(b) == 0;
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
bool CBaseBlob<BITS>::operator!=(const CBaseBlob& b) const
|
||||
{
|
||||
return !(*this == b);
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
bool CBaseBlob<BITS>::IsNull() const
|
||||
{
|
||||
return std::all_of(begin(), end(), [](uint8_t e) { return e == 0; });
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
void CBaseBlob<BITS>::SetNull()
|
||||
{
|
||||
data.fill(0);
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
std::string CBaseBlob<BITS>::GetHex(bool reverse) const
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << std::hex;
|
||||
if (reverse) {
|
||||
for (auto it = data.rbegin(); it != data.rend(); ++it)
|
||||
ss << std::setw(2) << std::setfill('0') << uint32_t(*it);
|
||||
}
|
||||
else {
|
||||
for (auto it = data.begin(); it != data.end(); ++it)
|
||||
ss << std::setw(2) << std::setfill('0') << uint32_t(*it);
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
void CBaseBlob<BITS>::SetHex(const char* psz)
|
||||
{
|
||||
SetNull();
|
||||
|
||||
// skip leading spaces
|
||||
while (isspace(*psz))
|
||||
psz++;
|
||||
|
||||
// skip 0x
|
||||
if (psz[0] == '0' && tolower(psz[1]) == 'x')
|
||||
psz += 2;
|
||||
|
||||
auto b = psz;
|
||||
// advance to end
|
||||
while (isxdigit(*psz))
|
||||
psz++;
|
||||
|
||||
--psz;
|
||||
char buf[3] = {};
|
||||
auto it = begin();
|
||||
while (psz >= b && it != end()) {
|
||||
buf[1] = *psz--;
|
||||
buf[0] = psz >= b ? *psz-- : '0';
|
||||
*it++ = std::strtoul(buf, nullptr, 16);
|
||||
}
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
uint64_t CBaseBlob<BITS>::GetUint64(int pos) const
|
||||
{
|
||||
assert((pos + 1) * 8 <= size());
|
||||
const uint8_t* ptr = begin() + pos * 8;
|
||||
uint64_t res = 0;
|
||||
for (int i = 0; i < 8; ++i)
|
||||
res |= (uint64_t(ptr[i]) << (8 * i));
|
||||
return res;
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
void CBaseBlob<BITS>::SetHex(const std::string& str)
|
||||
{
|
||||
SetHex(str.c_str());
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
std::string CBaseBlob<BITS>::ToString() const
|
||||
{
|
||||
return GetHex();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
uint8_t* CBaseBlob<BITS>::begin() noexcept
|
||||
{
|
||||
return data.data();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
const uint8_t* CBaseBlob<BITS>::begin() const noexcept
|
||||
{
|
||||
return data.data();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
uint8_t* CBaseBlob<BITS>::end() noexcept
|
||||
{
|
||||
return data.data() + data.size();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
const uint8_t* CBaseBlob<BITS>::end() const noexcept
|
||||
{
|
||||
return data.data() + data.size();
|
||||
}
|
||||
|
||||
template<uint32_t BITS>
|
||||
std::size_t CBaseBlob<BITS>::size() const
|
||||
{
|
||||
return data.size();
|
||||
}
|
||||
|
||||
template class CBaseBlob<160>;
|
||||
template class CBaseBlob<256>;
|
||||
@@ -1,50 +0,0 @@
|
||||
|
||||
#ifndef CLAIMTRIE_BLOB_H
|
||||
#define CLAIMTRIE_BLOB_H
|
||||
|
||||
#include <array>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/** Template base class for fixed-sized opaque blobs. */
|
||||
template<uint32_t BITS>
|
||||
class CBaseBlob
|
||||
{
|
||||
std::array<uint8_t, BITS / 8> data;
|
||||
public:
|
||||
CBaseBlob();
|
||||
|
||||
explicit CBaseBlob(const std::vector<uint8_t>& vec);
|
||||
|
||||
CBaseBlob(CBaseBlob&&) = default;
|
||||
CBaseBlob& operator=(CBaseBlob&&) = default;
|
||||
|
||||
CBaseBlob(const CBaseBlob& o);
|
||||
CBaseBlob& operator=(const CBaseBlob& o);
|
||||
|
||||
int Compare(const CBaseBlob& b) const;
|
||||
bool operator<(const CBaseBlob& b) const;
|
||||
bool operator==(const CBaseBlob& b) const;
|
||||
bool operator!=(const CBaseBlob& b) const;
|
||||
|
||||
uint8_t* begin() noexcept;
|
||||
const uint8_t* begin() const noexcept;
|
||||
|
||||
uint8_t* end() noexcept;
|
||||
const uint8_t* end() const noexcept;
|
||||
|
||||
std::size_t size() const;
|
||||
|
||||
bool IsNull() const;
|
||||
void SetNull();
|
||||
|
||||
std::string GetHex(bool reverse=true) const;
|
||||
void SetHex(const char* psz);
|
||||
void SetHex(const std::string& str);
|
||||
|
||||
std::string ToString() const;
|
||||
|
||||
uint64_t GetUint64(int pos) const;
|
||||
};
|
||||
|
||||
#endif // CLAIMTRIE_BLOB_H
|
||||
@@ -1,123 +0,0 @@
|
||||
|
||||
#include <data.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
|
||||
CClaimValue::CClaimValue(COutPoint outPoint, uint160 claimId, int64_t nAmount, int nHeight, int nValidAtHeight)
|
||||
: outPoint(std::move(outPoint)), claimId(std::move(claimId)), nAmount(nAmount), nEffectiveAmount(nAmount), nHeight(nHeight), nValidAtHeight(nValidAtHeight)
|
||||
{
|
||||
}
|
||||
|
||||
bool CClaimValue::operator<(const CClaimValue& other) const
|
||||
{
|
||||
if (nEffectiveAmount < other.nEffectiveAmount)
|
||||
return true;
|
||||
if (nEffectiveAmount != other.nEffectiveAmount)
|
||||
return false;
|
||||
if (nHeight > other.nHeight)
|
||||
return true;
|
||||
if (nHeight != other.nHeight)
|
||||
return false;
|
||||
return outPoint != other.outPoint && !(outPoint < other.outPoint);
|
||||
}
|
||||
|
||||
bool CClaimValue::operator==(const CClaimValue& other) const
|
||||
{
|
||||
return outPoint == other.outPoint && claimId == other.claimId && nAmount == other.nAmount && nHeight == other.nHeight && nValidAtHeight == other.nValidAtHeight;
|
||||
}
|
||||
|
||||
bool CClaimValue::operator!=(const CClaimValue& other) const
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
std::string CClaimValue::ToString() const
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "CClaimValue(" << outPoint.ToString()
|
||||
<< ", " << claimId.ToString()
|
||||
<< ", " << nAmount
|
||||
<< ", " << nEffectiveAmount
|
||||
<< ", " << nHeight
|
||||
<< ", " << nValidAtHeight << ')';
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
CSupportValue::CSupportValue(COutPoint outPoint, uint160 supportedClaimId, int64_t nAmount, int nHeight, int nValidAtHeight)
|
||||
: outPoint(std::move(outPoint)), supportedClaimId(std::move(supportedClaimId)), nAmount(nAmount), nHeight(nHeight), nValidAtHeight(nValidAtHeight)
|
||||
{
|
||||
}
|
||||
|
||||
bool CSupportValue::operator==(const CSupportValue& other) const
|
||||
{
|
||||
return outPoint == other.outPoint && supportedClaimId == other.supportedClaimId && nAmount == other.nAmount && nHeight == other.nHeight && nValidAtHeight == other.nValidAtHeight;
|
||||
}
|
||||
|
||||
bool CSupportValue::operator!=(const CSupportValue& other) const
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
std::string CSupportValue::ToString() const
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "CSupportValue(" << outPoint.ToString()
|
||||
<< ", " << supportedClaimId.ToString()
|
||||
<< ", " << nAmount
|
||||
<< ", " << nHeight
|
||||
<< ", " << nValidAtHeight << ')';
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
CNameOutPointHeightType::CNameOutPointHeightType(std::string name, COutPoint outPoint, int nValidHeight)
|
||||
: name(std::move(name)), outPoint(std::move(outPoint)), nValidHeight(nValidHeight)
|
||||
{
|
||||
}
|
||||
|
||||
CClaimNsupports::CClaimNsupports(CClaimValue claim, int64_t effectiveAmount, int originalHeight, std::vector<CSupportValue> supports)
|
||||
: claim(std::move(claim)), effectiveAmount(effectiveAmount), originalHeight(originalHeight), supports(std::move(supports))
|
||||
{
|
||||
}
|
||||
|
||||
bool CClaimNsupports::IsNull() const
|
||||
{
|
||||
return claim.claimId.IsNull();
|
||||
}
|
||||
|
||||
CClaimSupportToName::CClaimSupportToName(std::string name, int nLastTakeoverHeight, std::vector<CClaimNsupports> claimsNsupports, std::vector<CSupportValue> unmatchedSupports)
|
||||
: name(std::move(name)), nLastTakeoverHeight(nLastTakeoverHeight), claimsNsupports(std::move(claimsNsupports)), unmatchedSupports(std::move(unmatchedSupports))
|
||||
{
|
||||
}
|
||||
|
||||
static const CClaimNsupports invalid;
|
||||
|
||||
const CClaimNsupports& CClaimSupportToName::find(const uint160& claimId) const
|
||||
{
|
||||
auto it = std::find_if(claimsNsupports.begin(), claimsNsupports.end(), [&claimId](const CClaimNsupports& value) {
|
||||
return claimId == value.claim.claimId;
|
||||
});
|
||||
return it != claimsNsupports.end() ? *it : invalid;
|
||||
}
|
||||
|
||||
const CClaimNsupports& CClaimSupportToName::find(const std::string& partialId) const
|
||||
{
|
||||
std::string lowered(partialId);
|
||||
for (auto& c: lowered)
|
||||
c = std::tolower(c);
|
||||
|
||||
auto it = std::find_if(claimsNsupports.begin(), claimsNsupports.end(), [&lowered](const CClaimNsupports& value) {
|
||||
return value.claim.claimId.GetHex().find(lowered) == 0;
|
||||
});
|
||||
return it != claimsNsupports.end() ? *it : invalid;
|
||||
}
|
||||
|
||||
bool CClaimNsupports::operator<(const CClaimNsupports& other) const
|
||||
{
|
||||
return claim < other.claim;
|
||||
}
|
||||
|
||||
CClaimTrieProofNode::CClaimTrieProofNode(std::vector<std::pair<unsigned char, uint256>> children, bool hasValue, uint256 valHash)
|
||||
: children(std::move(children)), hasValue(hasValue), valHash(std::move(valHash))
|
||||
{
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
|
||||
#ifndef CLAIMTRIE_DATA_H
|
||||
#define CLAIMTRIE_DATA_H
|
||||
|
||||
#include <txoutpoint.h>
|
||||
#include <uints.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct CClaimValue
|
||||
{
|
||||
COutPoint outPoint;
|
||||
uint160 claimId;
|
||||
int64_t nAmount = 0;
|
||||
int64_t nEffectiveAmount = 0;
|
||||
int nHeight = 0;
|
||||
int nValidAtHeight = 0;
|
||||
|
||||
CClaimValue() = default;
|
||||
CClaimValue(COutPoint outPoint, uint160 claimId, int64_t nAmount, int nHeight, int nValidAtHeight);
|
||||
|
||||
CClaimValue(CClaimValue&&) = default;
|
||||
CClaimValue(const CClaimValue&) = default;
|
||||
CClaimValue& operator=(CClaimValue&&) = default;
|
||||
CClaimValue& operator=(const CClaimValue&) = default;
|
||||
|
||||
bool operator<(const CClaimValue& other) const;
|
||||
bool operator==(const CClaimValue& other) const;
|
||||
bool operator!=(const CClaimValue& other) const;
|
||||
|
||||
std::string ToString() const;
|
||||
};
|
||||
|
||||
struct CSupportValue
|
||||
{
|
||||
COutPoint outPoint;
|
||||
uint160 supportedClaimId;
|
||||
int64_t nAmount = 0;
|
||||
int nHeight = 0;
|
||||
int nValidAtHeight = 0;
|
||||
|
||||
CSupportValue() = default;
|
||||
CSupportValue(COutPoint outPoint, uint160 supportedClaimId, int64_t nAmount, int nHeight, int nValidAtHeight);
|
||||
|
||||
CSupportValue(CSupportValue&&) = default;
|
||||
CSupportValue(const CSupportValue&) = default;
|
||||
CSupportValue& operator=(CSupportValue&&) = default;
|
||||
CSupportValue& operator=(const CSupportValue&) = default;
|
||||
|
||||
bool operator==(const CSupportValue& other) const;
|
||||
bool operator!=(const CSupportValue& other) const;
|
||||
|
||||
std::string ToString() const;
|
||||
};
|
||||
|
||||
typedef std::vector<CClaimValue> claimEntryType;
|
||||
typedef std::vector<CSupportValue> supportEntryType;
|
||||
|
||||
struct CNameOutPointHeightType
|
||||
{
|
||||
std::string name;
|
||||
COutPoint outPoint;
|
||||
int nValidHeight = 0;
|
||||
|
||||
CNameOutPointHeightType() = default;
|
||||
CNameOutPointHeightType(std::string name, COutPoint outPoint, int nValidHeight);
|
||||
};
|
||||
|
||||
struct CClaimNsupports
|
||||
{
|
||||
CClaimNsupports() = default;
|
||||
CClaimNsupports(CClaimNsupports&&) = default;
|
||||
CClaimNsupports(const CClaimNsupports&) = default;
|
||||
|
||||
bool operator<(const CClaimNsupports& other) const;
|
||||
CClaimNsupports& operator=(CClaimNsupports&&) = default;
|
||||
CClaimNsupports& operator=(const CClaimNsupports&) = default;
|
||||
|
||||
CClaimNsupports(CClaimValue claim, int64_t effectiveAmount, int originalHeight,
|
||||
std::vector<CSupportValue> supports = {});
|
||||
|
||||
bool IsNull() const;
|
||||
|
||||
CClaimValue claim;
|
||||
int64_t effectiveAmount = 0;
|
||||
int originalHeight = -1;
|
||||
std::vector<CSupportValue> supports;
|
||||
};
|
||||
|
||||
struct CClaimSupportToName
|
||||
{
|
||||
CClaimSupportToName(std::string name, int nLastTakeoverHeight, std::vector<CClaimNsupports> claimsNsupports, std::vector<CSupportValue> unmatchedSupports);
|
||||
|
||||
const CClaimNsupports& find(const uint160& claimId) const;
|
||||
const CClaimNsupports& find(const std::string& partialId) const;
|
||||
|
||||
const std::string name;
|
||||
const int nLastTakeoverHeight;
|
||||
const std::vector<CClaimNsupports> claimsNsupports;
|
||||
const std::vector<CSupportValue> unmatchedSupports;
|
||||
};
|
||||
|
||||
struct CClaimTrieProofNode
|
||||
{
|
||||
CClaimTrieProofNode(std::vector<std::pair<unsigned char, uint256>> children, bool hasValue, uint256 valHash);
|
||||
|
||||
CClaimTrieProofNode() = default;
|
||||
CClaimTrieProofNode(CClaimTrieProofNode&&) = default;
|
||||
CClaimTrieProofNode(const CClaimTrieProofNode&) = default;
|
||||
CClaimTrieProofNode& operator=(CClaimTrieProofNode&&) = default;
|
||||
CClaimTrieProofNode& operator=(const CClaimTrieProofNode&) = default;
|
||||
|
||||
std::vector<std::pair<unsigned char, uint256>> children;
|
||||
bool hasValue;
|
||||
uint256 valHash;
|
||||
};
|
||||
|
||||
struct CClaimTrieProof
|
||||
{
|
||||
CClaimTrieProof() = default;
|
||||
CClaimTrieProof(CClaimTrieProof&&) = default;
|
||||
CClaimTrieProof(const CClaimTrieProof&) = default;
|
||||
CClaimTrieProof& operator=(CClaimTrieProof&&) = default;
|
||||
CClaimTrieProof& operator=(const CClaimTrieProof&) = default;
|
||||
|
||||
std::vector<std::pair<bool, uint256>> pairs;
|
||||
std::vector<CClaimTrieProofNode> nodes;
|
||||
int nHeightOfLastTakeover = 0;
|
||||
bool hasValue = false;
|
||||
COutPoint outPoint;
|
||||
};
|
||||
|
||||
#endif // CLAIMTRIE_DATA_H
|
||||
@@ -1,417 +0,0 @@
|
||||
|
||||
#include <forks.h>
|
||||
#include <hashes.h>
|
||||
#include <log.h>
|
||||
#include <trie.h>
|
||||
|
||||
#include <boost/locale.hpp>
|
||||
#include <boost/locale/conversion.hpp>
|
||||
#include <boost/locale/localization_backend.hpp>
|
||||
|
||||
#define logPrint CLogPrint::global()
|
||||
|
||||
CClaimTrieCacheExpirationFork::CClaimTrieCacheExpirationFork(CClaimTrie* base) : CClaimTrieCacheBase(base)
|
||||
{
|
||||
expirationHeight = nNextHeight;
|
||||
}
|
||||
|
||||
int CClaimTrieCacheExpirationFork::expirationTime() const
|
||||
{
|
||||
if (expirationHeight < base->nExtendedClaimExpirationForkHeight)
|
||||
return CClaimTrieCacheBase::expirationTime();
|
||||
return base->nExtendedClaimExpirationTime;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheExpirationFork::incrementBlock()
|
||||
{
|
||||
if (CClaimTrieCacheBase::incrementBlock()) {
|
||||
expirationHeight = nNextHeight;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheExpirationFork::decrementBlock()
|
||||
{
|
||||
if (CClaimTrieCacheBase::decrementBlock()) {
|
||||
expirationHeight = nNextHeight;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheExpirationFork::initializeIncrement()
|
||||
{
|
||||
// we could do this in the constructor, but that would not allow for multiple increments in a row (as done in unit tests)
|
||||
if (nNextHeight != base->nExtendedClaimExpirationForkHeight)
|
||||
return;
|
||||
|
||||
forkForExpirationChange(true);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheExpirationFork::finalizeDecrement()
|
||||
{
|
||||
auto ret = CClaimTrieCacheBase::finalizeDecrement();
|
||||
if (ret && nNextHeight == base->nExtendedClaimExpirationForkHeight)
|
||||
forkForExpirationChange(false);
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheExpirationFork::forkForExpirationChange(bool increment)
|
||||
{
|
||||
ensureTransacting();
|
||||
|
||||
/*
|
||||
If increment is True, we have forked to extend the expiration time, thus items in the expiration queue
|
||||
will have their expiration extended by "new expiration time - original expiration time"
|
||||
|
||||
If increment is False, we are decremented a block to reverse the fork. Thus items in the expiration queue
|
||||
will have their expiration extension removed.
|
||||
*/
|
||||
|
||||
auto height = nNextHeight;
|
||||
int extension = base->nExtendedClaimExpirationTime - base->nOriginalClaimExpirationTime;
|
||||
if (!increment) {
|
||||
height += extension;
|
||||
extension *= -1;
|
||||
}
|
||||
|
||||
db << "UPDATE claim SET expirationHeight = expirationHeight + ? WHERE expirationHeight >= ?" << extension << height;
|
||||
db << "UPDATE support SET expirationHeight = expirationHeight + ? WHERE expirationHeight >= ?" << extension << height;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
CClaimTrieCacheNormalizationFork::CClaimTrieCacheNormalizationFork(CClaimTrie* base) : CClaimTrieCacheExpirationFork(base)
|
||||
{
|
||||
db.define("NORMALIZED", [this](const std::string& str) { return normalizeClaimName(str, true); });
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::shouldNormalize() const
|
||||
{
|
||||
return nNextHeight > base->nNormalizedNameForkHeight;
|
||||
}
|
||||
|
||||
std::string CClaimTrieCacheNormalizationFork::normalizeClaimName(const std::string& name, bool force) const
|
||||
{
|
||||
if (!force && !shouldNormalize())
|
||||
return name;
|
||||
|
||||
static std::locale utf8;
|
||||
static bool initialized = false;
|
||||
if (!initialized) {
|
||||
static boost::locale::localization_backend_manager manager =
|
||||
boost::locale::localization_backend_manager::global();
|
||||
manager.select("icu");
|
||||
|
||||
static boost::locale::generator curLocale(manager);
|
||||
utf8 = curLocale("en_US.UTF8");
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
std::string normalized;
|
||||
try {
|
||||
// Check if it is a valid utf-8 string. If not, it will throw a
|
||||
// boost::locale::conv::conversion_error exception which we catch later
|
||||
normalized = boost::locale::conv::to_utf<char>(name, "UTF-8", boost::locale::conv::stop);
|
||||
if (normalized.empty())
|
||||
return name;
|
||||
|
||||
// these methods supposedly only use the "UTF8" portion of the locale object:
|
||||
normalized = boost::locale::normalize(normalized, boost::locale::norm_nfd, utf8);
|
||||
normalized = boost::locale::fold_case(normalized, utf8);
|
||||
} catch (const boost::locale::conv::conversion_error& e) {
|
||||
return name;
|
||||
} catch (const std::bad_cast& e) {
|
||||
logPrint << "CClaimTrieCacheNormalizationFork::" << __func__ << "() is invalid or dependencies are missing: " << e.what() << Clog::endl;
|
||||
throw;
|
||||
} catch (const std::exception& e) { // TODO: change to use ... with current_exception() in c++11
|
||||
logPrint << "CClaimTrieCacheNormalizationFork::" << __func__ << "() had an unexpected exception: " << e.what() << Clog::endl;
|
||||
return name;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::normalizeAllNamesInTrieIfNecessary()
|
||||
{
|
||||
ensureTransacting();
|
||||
|
||||
// make the new nodes
|
||||
db << "INSERT INTO node(name) SELECT NORMALIZED(name) AS nn FROM claim WHERE nn != nodeName "
|
||||
"AND activationHeight <= ?1 AND expirationHeight > ?1 ON CONFLICT(name) DO UPDATE SET hash = NULL" << nNextHeight;
|
||||
|
||||
// there's a subtlety here: names in supports don't make new nodes
|
||||
db << "UPDATE node SET hash = NULL WHERE name IN "
|
||||
"(SELECT NORMALIZED(name) AS nn FROM support WHERE nn != nodeName "
|
||||
"AND activationHeight <= ?1 AND expirationHeight > ?1)" << nNextHeight;
|
||||
|
||||
// update the claims and supports
|
||||
db << "UPDATE claim SET nodeName = NORMALIZED(name) WHERE activationHeight <= ?1 AND expirationHeight > ?1" << nNextHeight;
|
||||
db << "UPDATE support SET nodeName = NORMALIZED(name) WHERE activationHeight <= ?1 AND expirationHeight > ?1" << nNextHeight;
|
||||
|
||||
// remove the old nodes
|
||||
db << "UPDATE node SET hash = NULL WHERE name NOT IN "
|
||||
"(SELECT nodeName FROM claim WHERE activationHeight <= ?1 AND expirationHeight > ?1 "
|
||||
"UNION SELECT nodeName FROM support WHERE activationHeight <= ?1 AND expirationHeight > ?1)" << nNextHeight;
|
||||
|
||||
// work around a bug in the old implementation:
|
||||
db << "UPDATE claim SET activationHeight = ?1 " // force a takeover on these
|
||||
"WHERE updateHeight < ?1 AND activationHeight > ?1 AND nodeName != name" << nNextHeight;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::unnormalizeAllNamesInTrieIfNecessary()
|
||||
{
|
||||
ensureTransacting();
|
||||
|
||||
db << "INSERT INTO node(name) SELECT name FROM claim WHERE name != nodeName "
|
||||
"AND activationHeight < ?1 AND expirationHeight > ?1 ON CONFLICT(name) DO UPDATE SET hash = NULL" << nNextHeight;
|
||||
|
||||
db << "UPDATE node SET hash = NULL WHERE name IN "
|
||||
"(SELECT nodeName FROM support WHERE name != nodeName "
|
||||
"UNION SELECT nodeName FROM claim WHERE name != nodeName)";
|
||||
|
||||
db << "UPDATE claim SET nodeName = name";
|
||||
db << "UPDATE support SET nodeName = name";
|
||||
|
||||
// we need to let the tree structure method do the actual node delete
|
||||
db << "UPDATE node SET hash = NULL WHERE name NOT IN "
|
||||
"(SELECT DISTINCT name FROM claim)";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::incrementBlock()
|
||||
{
|
||||
if (nNextHeight == base->nNormalizedNameForkHeight)
|
||||
normalizeAllNamesInTrieIfNecessary();
|
||||
return CClaimTrieCacheExpirationFork::incrementBlock();
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::decrementBlock()
|
||||
{
|
||||
auto ret = CClaimTrieCacheExpirationFork::decrementBlock();
|
||||
if (ret && nNextHeight == base->nNormalizedNameForkHeight)
|
||||
unnormalizeAllNamesInTrieIfNecessary();
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof)
|
||||
{
|
||||
return CClaimTrieCacheExpirationFork::getProofForName(normalizeClaimName(name), claim, proof);
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheNormalizationFork::getInfoForName(const std::string& name, CClaimValue& claim, int offsetHeight) const
|
||||
{
|
||||
return CClaimTrieCacheExpirationFork::getInfoForName(normalizeClaimName(name), claim, offsetHeight);
|
||||
}
|
||||
|
||||
CClaimSupportToName CClaimTrieCacheNormalizationFork::getClaimsForName(const std::string& name) const
|
||||
{
|
||||
return CClaimTrieCacheExpirationFork::getClaimsForName(normalizeClaimName(name));
|
||||
}
|
||||
|
||||
int CClaimTrieCacheNormalizationFork::getDelayForName(const std::string& name, const uint160& claimId) const
|
||||
{
|
||||
return CClaimTrieCacheExpirationFork::getDelayForName(normalizeClaimName(name), claimId);
|
||||
}
|
||||
|
||||
std::string CClaimTrieCacheNormalizationFork::adjustNameForValidHeight(const std::string& name, int validHeight) const
|
||||
{
|
||||
return normalizeClaimName(name, validHeight > base->nNormalizedNameForkHeight);
|
||||
}
|
||||
|
||||
CClaimTrieCacheHashFork::CClaimTrieCacheHashFork(CClaimTrie* base) : CClaimTrieCacheNormalizationFork(base)
|
||||
{
|
||||
}
|
||||
|
||||
static const auto leafHash = uint256S("0000000000000000000000000000000000000000000000000000000000000002");
|
||||
static const auto emptyHash = uint256S("0000000000000000000000000000000000000000000000000000000000000003");
|
||||
|
||||
uint256 ComputeMerkleRoot(std::vector<uint256> hashes)
|
||||
{
|
||||
while (hashes.size() > 1) {
|
||||
if (hashes.size() & 1)
|
||||
hashes.push_back(hashes.back());
|
||||
|
||||
sha256n_way(hashes);
|
||||
hashes.resize(hashes.size() / 2);
|
||||
}
|
||||
return hashes.empty() ? uint256{} : hashes[0];
|
||||
}
|
||||
|
||||
uint256 CClaimTrieCacheHashFork::computeNodeHash(const std::string& name, int takeoverHeight)
|
||||
{
|
||||
if (nNextHeight < base->nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrieCacheNormalizationFork::computeNodeHash(name, takeoverHeight);
|
||||
|
||||
std::vector<uint256> childHashes;
|
||||
childHashQuery << name >> [&childHashes](std::string, uint256 hash) {
|
||||
childHashes.push_back(std::move(hash));
|
||||
};
|
||||
childHashQuery++;
|
||||
|
||||
std::vector<uint256> claimHashes;
|
||||
//if (takeoverHeight > 0) {
|
||||
COutPoint p;
|
||||
for (auto &&row: claimHashQuery << nNextHeight << name) {
|
||||
row >> p.hash >> p.n;
|
||||
claimHashes.push_back(getValueHash(p, takeoverHeight));
|
||||
}
|
||||
claimHashQuery++;
|
||||
//}
|
||||
|
||||
auto left = childHashes.empty() ? leafHash : ComputeMerkleRoot(std::move(childHashes));
|
||||
auto right = claimHashes.empty() ? emptyHash : ComputeMerkleRoot(std::move(claimHashes));
|
||||
|
||||
return Hash(left.begin(), left.end(), right.begin(), right.end());
|
||||
}
|
||||
|
||||
std::vector<uint256> ComputeMerklePath(const std::vector<uint256>& hashes, uint32_t idx)
|
||||
{
|
||||
uint32_t count = 0;
|
||||
int matchlevel = -1;
|
||||
bool matchh = false;
|
||||
uint256 inner[32], h;
|
||||
const uint32_t one = 1;
|
||||
std::vector<uint256> res;
|
||||
|
||||
const auto iterateInner = [&](int& level) {
|
||||
for (; !(count & (one << level)); level++) {
|
||||
const auto& ihash = inner[level];
|
||||
if (matchh) {
|
||||
res.push_back(ihash);
|
||||
} else if (matchlevel == level) {
|
||||
res.push_back(h);
|
||||
matchh = true;
|
||||
}
|
||||
h = Hash(ihash.begin(), ihash.end(), h.begin(), h.end());
|
||||
}
|
||||
};
|
||||
|
||||
while (count < hashes.size()) {
|
||||
h = hashes[count];
|
||||
matchh = count == idx;
|
||||
count++;
|
||||
int level = 0;
|
||||
iterateInner(level);
|
||||
// Store the resulting hash at inner position level.
|
||||
inner[level] = h;
|
||||
if (matchh)
|
||||
matchlevel = level;
|
||||
}
|
||||
|
||||
int level = 0;
|
||||
while (!(count & (one << level)))
|
||||
level++;
|
||||
|
||||
h = inner[level];
|
||||
matchh = matchlevel == level;
|
||||
|
||||
while (count != (one << level)) {
|
||||
// If we reach this point, h is an inner value that is not the top.
|
||||
if (matchh)
|
||||
res.push_back(h);
|
||||
|
||||
h = Hash(h.begin(), h.end(), h.begin(), h.end());
|
||||
// Increment count to the value it would have if two entries at this
|
||||
count += (one << level);
|
||||
level++;
|
||||
iterateInner(level);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
extern const std::string proofClaimQuery_s;
|
||||
|
||||
bool CClaimTrieCacheHashFork::getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof)
|
||||
{
|
||||
if (nNextHeight < base->nAllClaimsInMerkleForkHeight)
|
||||
return CClaimTrieCacheNormalizationFork::getProofForName(name, claim, proof);
|
||||
|
||||
auto fillPairs = [&proof](const std::vector<uint256>& hashes, uint32_t idx) {
|
||||
auto partials = ComputeMerklePath(hashes, idx);
|
||||
for (int i = partials.size() - 1; i >= 0; --i)
|
||||
proof.pairs.emplace_back((idx >> i) & 1, partials[i]);
|
||||
};
|
||||
|
||||
// cache the parent nodes
|
||||
getMerkleHash();
|
||||
proof = CClaimTrieProof();
|
||||
for (auto&& row: db << proofClaimQuery_s << name) {
|
||||
std::string key;
|
||||
int takeoverHeight;
|
||||
row >> key >> takeoverHeight;
|
||||
uint32_t nextCurrentIdx = 0;
|
||||
std::vector<uint256> childHashes;
|
||||
for (auto&& child : childHashQuery << key) {
|
||||
std::string childKey;
|
||||
uint256 childHash;
|
||||
child >> childKey >> childHash;
|
||||
if (name.find(childKey) == 0)
|
||||
nextCurrentIdx = uint32_t(childHashes.size());
|
||||
childHashes.push_back(childHash);
|
||||
}
|
||||
childHashQuery++;
|
||||
|
||||
std::vector<uint256> claimHashes;
|
||||
uint32_t claimIdx = 0;
|
||||
for (auto&& child: claimHashQuery << nNextHeight << key) {
|
||||
COutPoint childOutPoint;
|
||||
uint160 childClaimID;
|
||||
child >> childOutPoint.hash >> childOutPoint.n >> childClaimID;
|
||||
if (childClaimID == claim && key == name) {
|
||||
claimIdx = uint32_t(claimHashes.size());
|
||||
proof.outPoint = childOutPoint;
|
||||
proof.hasValue = true;
|
||||
}
|
||||
claimHashes.push_back(getValueHash(childOutPoint, takeoverHeight));
|
||||
}
|
||||
claimHashQuery++;
|
||||
|
||||
// I am on a node; I need a hash(children, claims)
|
||||
// if I am the last node on the list, it will be hash(children, x)
|
||||
// else it will be hash(x, claims)
|
||||
if (key == name) {
|
||||
proof.nHeightOfLastTakeover = takeoverHeight;
|
||||
auto hash = childHashes.empty() ? leafHash : ComputeMerkleRoot(std::move(childHashes));
|
||||
proof.pairs.emplace_back(true, hash);
|
||||
if (!claimHashes.empty())
|
||||
fillPairs(claimHashes, claimIdx);
|
||||
} else {
|
||||
auto hash = claimHashes.empty() ? emptyHash : ComputeMerkleRoot(std::move(claimHashes));
|
||||
proof.pairs.emplace_back(false, hash);
|
||||
if (!childHashes.empty())
|
||||
fillPairs(childHashes, nextCurrentIdx);
|
||||
}
|
||||
}
|
||||
std::reverse(proof.pairs.begin(), proof.pairs.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheHashFork::initializeIncrement()
|
||||
{
|
||||
CClaimTrieCacheNormalizationFork::initializeIncrement();
|
||||
// we could do this in the constructor, but that would not allow for multiple increments in a row (as done in unit tests)
|
||||
if (nNextHeight == base->nAllClaimsInMerkleForkHeight - 1) {
|
||||
ensureTransacting();
|
||||
db << "UPDATE node SET hash = NULL";
|
||||
}
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::finalizeDecrement()
|
||||
{
|
||||
auto ret = CClaimTrieCacheNormalizationFork::finalizeDecrement();
|
||||
if (ret && nNextHeight == base->nAllClaimsInMerkleForkHeight - 1) {
|
||||
ensureTransacting();
|
||||
db << "UPDATE node SET hash = NULL";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheHashFork::allowSupportMetadata() const
|
||||
{
|
||||
return nNextHeight >= base->nAllClaimsInMerkleForkHeight;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
|
||||
#ifndef CLAIMTRIE_FORKS_H
|
||||
#define CLAIMTRIE_FORKS_H
|
||||
|
||||
#include <trie.h>
|
||||
|
||||
class CClaimTrieCacheExpirationFork : public CClaimTrieCacheBase
|
||||
{
|
||||
public:
|
||||
explicit CClaimTrieCacheExpirationFork(CClaimTrie* base);
|
||||
|
||||
int expirationTime() const override;
|
||||
|
||||
virtual void initializeIncrement();
|
||||
bool incrementBlock() override;
|
||||
bool decrementBlock() override;
|
||||
bool finalizeDecrement() override;
|
||||
|
||||
protected:
|
||||
int expirationHeight;
|
||||
|
||||
private:
|
||||
bool forkForExpirationChange(bool increment);
|
||||
};
|
||||
|
||||
class CClaimTrieCacheNormalizationFork : public CClaimTrieCacheExpirationFork
|
||||
{
|
||||
public:
|
||||
explicit CClaimTrieCacheNormalizationFork(CClaimTrie* base);
|
||||
|
||||
bool shouldNormalize() const;
|
||||
|
||||
// lower-case and normalize any input string name
|
||||
// see: https://unicode.org/reports/tr15/#Norm_Forms
|
||||
std::string normalizeClaimName(const std::string& name, bool force = false) const; // public only for validating name field on update op
|
||||
|
||||
bool incrementBlock() override;
|
||||
bool decrementBlock() override;
|
||||
|
||||
bool getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof) override;
|
||||
bool getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset = 0) const override;
|
||||
CClaimSupportToName getClaimsForName(const std::string& name) const override;
|
||||
std::string adjustNameForValidHeight(const std::string& name, int validHeight) const override;
|
||||
|
||||
protected:
|
||||
int getDelayForName(const std::string& name, const uint160& claimId) const override;
|
||||
|
||||
private:
|
||||
bool normalizeAllNamesInTrieIfNecessary();
|
||||
bool unnormalizeAllNamesInTrieIfNecessary();
|
||||
};
|
||||
|
||||
class CClaimTrieCacheHashFork : public CClaimTrieCacheNormalizationFork
|
||||
{
|
||||
public:
|
||||
explicit CClaimTrieCacheHashFork(CClaimTrie* base);
|
||||
|
||||
bool getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof) override;
|
||||
void initializeIncrement() override;
|
||||
bool finalizeDecrement() override;
|
||||
|
||||
bool allowSupportMetadata() const;
|
||||
|
||||
protected:
|
||||
uint256 computeNodeHash(const std::string& name, int takeoverHeight) override;
|
||||
};
|
||||
|
||||
typedef CClaimTrieCacheHashFork CClaimTrieCache;
|
||||
|
||||
#endif // CLAIMTRIE_FORKS_H
|
||||
@@ -1,21 +0,0 @@
|
||||
|
||||
#include <hashes.h>
|
||||
|
||||
// Bitcoin doubles hash
|
||||
uint256 CalcHash(SHA256_CTX* sha)
|
||||
{
|
||||
uint256 result;
|
||||
SHA256_Final(result.begin(), sha);
|
||||
SHA256_Init(sha);
|
||||
SHA256_Update(sha, result.begin(), result.size());
|
||||
SHA256_Final(result.begin(), sha);
|
||||
return result;
|
||||
}
|
||||
|
||||
// universal N way hash function
|
||||
std::function<void(std::vector<uint256>&)> sha256n_way =
|
||||
[](std::vector<uint256>& hashes) {
|
||||
for (std::size_t i = 0, j = 0; i < hashes.size(); i += 2)
|
||||
hashes[j++] = Hash(hashes[i].begin(), hashes[i].end(),
|
||||
hashes[i+1].begin(), hashes[i+1].end());
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
|
||||
#ifndef CLAIMTRIE_HASHES_H
|
||||
#define CLAIMTRIE_HASHES_H
|
||||
|
||||
#include <openssl/sha.h>
|
||||
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include <uints.h>
|
||||
|
||||
uint256 CalcHash(SHA256_CTX* sha);
|
||||
|
||||
template<typename TIterator, typename... Args>
|
||||
uint256 CalcHash(SHA256_CTX* sha, TIterator begin, TIterator end, Args... args)
|
||||
{
|
||||
static uint8_t blank;
|
||||
SHA256_Update(sha, begin == end ? &blank : (uint8_t*)&begin[0], std::distance(begin, end) * sizeof(begin[0]));
|
||||
return CalcHash(sha, args...);
|
||||
}
|
||||
|
||||
template<typename TIterator, typename... Args>
|
||||
uint256 Hash(TIterator begin, TIterator end, Args... args)
|
||||
{
|
||||
static_assert((sizeof...(args) & 1) != 1, "Parameters should be even number");
|
||||
SHA256_CTX sha;
|
||||
SHA256_Init(&sha);
|
||||
return CalcHash(&sha, begin, end, args...);
|
||||
}
|
||||
|
||||
extern std::function<void(std::vector<uint256>&)> sha256n_way;
|
||||
|
||||
#endif // CLAIMTRIE_HASHES_H
|
||||
@@ -1,75 +0,0 @@
|
||||
|
||||
%module(directors="1") libclaimtrie
|
||||
%{
|
||||
#include "blob.h"
|
||||
#include "uints.h"
|
||||
#include "txoutpoint.h"
|
||||
#include "data.h"
|
||||
#include "trie.h"
|
||||
#include "forks.h"
|
||||
%}
|
||||
|
||||
%feature("flatnested", 1);
|
||||
%feature("director") CIterateCallback;
|
||||
|
||||
%include stl.i
|
||||
%include stdint.i
|
||||
%include typemaps.i
|
||||
|
||||
%apply int& OUTPUT { int& nValidAtHeight };
|
||||
|
||||
%ignore CBaseBlob(CBaseBlob &&);
|
||||
%ignore CClaimNsupports(CClaimNsupports &&);
|
||||
%ignore CClaimTrieProof(CClaimTrieProof &&);
|
||||
%ignore CClaimTrieProofNode(CClaimTrieProofNode &&);
|
||||
%ignore CClaimValue(CClaimValue &&);
|
||||
%ignore COutPoint(COutPoint &&);
|
||||
%ignore CSupportValue(CSupportValue &&);
|
||||
%ignore uint160(uint160 &&);
|
||||
%ignore uint256(uint256 &&);
|
||||
|
||||
%template(vecUint8) std::vector<uint8_t>;
|
||||
|
||||
%include "blob.h"
|
||||
|
||||
%template(blob160) CBaseBlob<160>;
|
||||
%template(blob256) CBaseBlob<256>;
|
||||
|
||||
%include "uints.h"
|
||||
%include "txoutpoint.h"
|
||||
%include "data.h"
|
||||
|
||||
%rename(CClaimTrieCache) CClaimTrieCacheHashFork;
|
||||
|
||||
%include "trie.h"
|
||||
%include "forks.h"
|
||||
|
||||
%template(claimEntryType) std::vector<CClaimValue>;
|
||||
%template(supportEntryType) std::vector<CSupportValue>;
|
||||
%template(claimsNsupports) std::vector<CClaimNsupports>;
|
||||
|
||||
%template(proofPair) std::pair<bool, uint256>;
|
||||
%template(proofNodePair) std::pair<unsigned char, uint256>;
|
||||
|
||||
%template(proofNodes) std::vector<CClaimTrieProofNode>;
|
||||
%template(proofPairs) std::vector<std::pair<bool, uint256>>;
|
||||
%template(proofNodeChildren) std::vector<std::pair<unsigned char, uint256>>;
|
||||
|
||||
%inline %{
|
||||
struct CIterateCallback {
|
||||
CIterateCallback() = default;
|
||||
virtual ~CIterateCallback() = default;
|
||||
virtual void apply(const std::string&) = 0;
|
||||
};
|
||||
|
||||
void getNamesInTrie(const CClaimTrieCache& cache, CIterateCallback* cb)
|
||||
{
|
||||
cache.getNamesInTrie([cb](const std::string& name) {
|
||||
cb->apply(name);
|
||||
});
|
||||
}
|
||||
%}
|
||||
|
||||
%typemap(in,numinputs=0) CClaimValue&, CClaimTrieProof& %{
|
||||
$1 = &$input;
|
||||
%}
|
||||
@@ -1,120 +0,0 @@
|
||||
|
||||
package main
|
||||
|
||||
import(
|
||||
"testing"
|
||||
."libclaimtrie"
|
||||
)
|
||||
|
||||
func assertEqual(t *testing.T, a interface{}, b interface{}, msg string) {
|
||||
if a != b {
|
||||
t.Fatalf("%s != %s, %s", a, b, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func assertNotEqual(t *testing.T, a interface{}, b interface{}, msg string) {
|
||||
if a == b {
|
||||
t.Fatalf("%s == %s, %s", a, b, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func assertFalse(t *testing.T, a interface{}, msg string) {
|
||||
if a != false {
|
||||
t.Fatalf("%s != false, %s", a, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func assertTrue(t *testing.T, a interface{}, msg string) {
|
||||
if a != true {
|
||||
t.Fatalf("%s != true, %s", a, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func assertClaimEqual(t *testing.T, claim CClaimValue, txo COutPoint, cid Uint160, amount int64, effe int64, height int, validHeight int, msg string) {
|
||||
assertEqual(t, claim.GetOutPoint(), txo, msg)
|
||||
assertEqual(t, claim.GetClaimId(), cid, msg)
|
||||
assertEqual(t, claim.GetNAmount(), amount, msg)
|
||||
assertEqual(t, claim.GetNEffectiveAmount(), effe, msg)
|
||||
assertEqual(t, claim.GetNHeight(), height, msg)
|
||||
assertEqual(t, claim.GetNValidAtHeight(), validHeight, msg)
|
||||
}
|
||||
|
||||
func assertSupportEqual(t *testing.T, support CSupportValue, txo COutPoint, cid Uint160, amount int64, height int, validHeight int, msg string) {
|
||||
assertEqual(t, support.GetOutPoint(), txo, msg)
|
||||
assertEqual(t, support.GetSupportedClaimId(), cid, msg)
|
||||
assertEqual(t, support.GetNAmount(), amount, msg)
|
||||
assertEqual(t, support.GetNHeight(), height, msg)
|
||||
assertEqual(t, support.GetNValidAtHeight(), validHeight, msg)
|
||||
}
|
||||
|
||||
var uint256s = "1234567890987654321012345678909876543210123456789098765432101234"
|
||||
var uint160 = Uint160S("1234567890987654321012345678909876543210")
|
||||
var uint256 = Uint256S(uint256s)
|
||||
var txp = NewCOutPoint(uint256, uint(1))
|
||||
|
||||
func Test_uint256(t *testing.T) {
|
||||
assertFalse(t, uint256.IsNull(), "incorrect uint256S or CBaseBlob::IsNull")
|
||||
assertEqual(t, uint256.GetHex(), uint256s, "incorrect CBaseBlob::GetHex")
|
||||
assertEqual(t, uint256.GetHex(), uint256.ToString(), "incorrect CBaseBlob::ToString")
|
||||
assertEqual(t, uint256.Size(), 32, "incorrect CBaseBlob::size")
|
||||
uint256c := NewUint256()
|
||||
assertNotEqual(t, uint256c, uint256, "incorrect CBaseBlob::operator!=")
|
||||
assertTrue(t, uint256c.IsNull(), "incorrect CBaseBlob::IsNull")
|
||||
uint256c = NewUint256(uint256)
|
||||
assertEqual(t, uint256c, uint256, "incorrect CBaseBlob::operator==")
|
||||
uint256c.SetNull()
|
||||
assertTrue(t, uint256c.IsNull(), "incorrect CBaseBlob::SetNull")
|
||||
}
|
||||
|
||||
func Test_txoupoint(t *testing.T) {
|
||||
assertEqual(t, txp.GetHash(), uint256, "incorrect COutPoint::COutPoint")
|
||||
assertEqual(t, txp.GetN(), 1, "incorrect COutPoint::COutPoint")
|
||||
assertFalse(t, txp.IsNull(), "incorrect COutPoint::IsNull")
|
||||
pcopy := NewCOutPoint()
|
||||
assertTrue(t, pcopy.IsNull(), "incorrect COutPoint::IsNull")
|
||||
assertEqual(t, pcopy.GetHash(), NewUint256(), "incorrect COutPoint::COutPoint")
|
||||
assertNotEqual(t, pcopy, txp, "incorrect COutPoint::operator!=")
|
||||
}
|
||||
|
||||
func Test_claim(t *testing.T) {
|
||||
assertEqual(t, uint160.Size(), 20, "incorrect CBaseBlob::size")
|
||||
claim := NewCClaimValue(txp, uint160, 20, 1, 10)
|
||||
assertClaimEqual(t, claim, txp, uint160, 20, 20, 1, 10, "incorrect CClaimValue::CClaimValue")
|
||||
}
|
||||
|
||||
func Test_support(t *testing.T) {
|
||||
claim := NewCClaimValue(txp, uint160, 20, 1, 10)
|
||||
support := NewCSupportValue(txp, uint160, 20, 1, 10)
|
||||
assertSupportEqual(t, support, claim.GetOutPoint(), claim.GetClaimId(), claim.GetNAmount(), claim.GetNHeight(), claim.GetNValidAtHeight(), "incorrect CSupportValue::CSupportValue")
|
||||
}
|
||||
|
||||
func Test_claimtrie(t *testing.T) {
|
||||
claim := NewCClaimValue(txp, uint160, 20, 0, 0)
|
||||
wipe := true; height := 1; data_dir := "."
|
||||
trie := NewCClaimTrie(10*1024*1024, wipe, height, data_dir)
|
||||
cache := NewCClaimTrieCache(trie)
|
||||
assertTrue(t, trie.Empty(), "incorrect CClaimtrieCache::empty")
|
||||
assertTrue(t, cache.AddClaim("test", txp, uint160, 20, 0, 0), "incorrect CClaimtrieCache::addClaim")
|
||||
assertTrue(t, cache.HaveClaim("test", txp), "incorrect CClaimtrieCache::haveClaim")
|
||||
assertEqual(t, cache.GetTotalNamesInTrie(), 1, "incorrect CClaimtrieCache::getTotalNamesInTrie")
|
||||
assertEqual(t, cache.GetTotalClaimsInTrie(), 1, "incorrect CClaimtrieCache::getTotalClaimsInTrie")
|
||||
var nValidAtHeight []int
|
||||
// add second claim
|
||||
txp.SetN(2)
|
||||
uint1601 := Uint160S("1234567890987654321012345678909876543211")
|
||||
assertTrue(t, cache.AddClaim("test", txp, uint1601, 20, 1, 1), "incorrect CClaimtrieCache::addClaim")
|
||||
result := cache.HaveClaimInQueue("test", txp, nValidAtHeight)
|
||||
assertTrue(t, result, "incorrect CClaimTrieCache::haveClaimInQueue")
|
||||
assertEqual(t, nValidAtHeight[0], 1, "incorrect CClaimTrieCache::haveClaimInQueue, nValidAtHeight")
|
||||
claim1 := NewCClaimValue()
|
||||
assertTrue(t, cache.GetInfoForName("test", claim1), "incorrect CClaimTrieCache::getInfoForName")
|
||||
assertEqual(t, claim, claim1, "incorrect CClaimtrieCache::getInfoForName")
|
||||
proof := NewCClaimTrieProof()
|
||||
assertTrue(t, cache.GetProofForName("test", uint160, proof), "incorrect CacheProofCallback")
|
||||
assertTrue(t, proof.GetHasValue(), "incorrect CClaimTrieCache::getProofForName")
|
||||
claimsToName := cache.GetClaimsForName("test")
|
||||
claims := claimsToName.GetClaimsNsupports()
|
||||
assertEqual(t, claims.Size(), 2, "incorrect CClaimTrieCache::getClaimsForName")
|
||||
assertFalse(t, claims.Get(0).IsNull(), "incorrect CClaimNsupports::IsNull")
|
||||
assertFalse(t, claims.Get(1).IsNull(), "incorrect CClaimNsupports::IsNull")
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
|
||||
from libclaimtrie import *
|
||||
import unittest
|
||||
|
||||
class CacheIterateCallback(CIterateCallback):
|
||||
def __init__(self, names):
|
||||
CIterateCallback.__init__(self)
|
||||
self.names = names
|
||||
|
||||
def apply(self, name):
|
||||
assert(name in self.names), "Incorrect trie names"
|
||||
|
||||
class TestClaimTrieTypes(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.uint256s = "1234567890987654321012345678909876543210123456789098765432101234"
|
||||
self.uint160 = uint160S("1234567890987654321012345678909876543210")
|
||||
self.uint = uint256S(self.uint256s)
|
||||
self.txp = COutPoint(self.uint, 1)
|
||||
|
||||
def assertClaimEqual(self, claim, txo, cid, amount, effe, height, validHeight, msg):
|
||||
self.assertEqual(claim.outPoint, txo, msg)
|
||||
self.assertEqual(claim.claimId, cid, msg)
|
||||
self.assertEqual(claim.nAmount, amount, msg)
|
||||
self.assertEqual(claim.nEffectiveAmount, effe, msg)
|
||||
self.assertEqual(claim.nHeight, height, msg)
|
||||
self.assertEqual(claim.nValidAtHeight, validHeight, msg)
|
||||
|
||||
def assertSupportEqual(self, support, txo, cid, amount, height, validHeight, msg):
|
||||
self.assertEqual(support.outPoint, txo, msg)
|
||||
self.assertEqual(support.supportedClaimId, cid, msg)
|
||||
self.assertEqual(support.nAmount, amount, msg)
|
||||
self.assertEqual(support.nHeight, height, msg)
|
||||
self.assertEqual(support.nValidAtHeight, validHeight, msg)
|
||||
|
||||
def test_uint256(self):
|
||||
uint = self.uint
|
||||
self.assertFalse(uint.IsNull(), "incorrect uint256S or CBaseBlob::IsNull")
|
||||
self.assertEqual(uint.GetHex(), self.uint256s, "incorrect CBaseBlob::GetHex")
|
||||
self.assertEqual(uint.GetHex(), uint.ToString(), "incorrect CBaseBlob::ToString")
|
||||
self.assertEqual(uint.size(), 32, "incorrect CBaseBlob::size")
|
||||
copy = uint256()
|
||||
self.assertNotEqual(copy, uint, "incorrect CBaseBlob::operator!=")
|
||||
self.assertTrue(copy.IsNull(), "incorrect CBaseBlob::IsNull")
|
||||
copy = uint256(uint)
|
||||
self.assertEqual(copy, uint, "incorrect CBaseBlob::operator==")
|
||||
copy.SetNull()
|
||||
self.assertTrue(copy.IsNull()), "incorrect CBaseBlob::SetNull"
|
||||
|
||||
def test_txoupoint(self):
|
||||
txp = self.txp
|
||||
uint = self.uint
|
||||
self.assertEqual(txp.hash, uint, "incorrect COutPoint::COutPoint")
|
||||
self.assertEqual(txp.n, 1, "incorrect COutPoint::COutPoint")
|
||||
self.assertFalse(txp.IsNull(), "incorrect COutPoint::IsNull")
|
||||
pcopy = COutPoint()
|
||||
self.assertTrue(pcopy.IsNull(), "incorrect COutPoint::IsNull")
|
||||
self.assertEqual(pcopy.hash, uint256(), "incorrect COutPoint::COutPoint")
|
||||
self.assertNotEqual(pcopy, txp, "incorrect COutPoint::operator!=")
|
||||
self.assertIn(uint.ToString()[:10], txp.ToString(), "incorrect COutPoint::ToString")
|
||||
|
||||
def test_claim(self):
|
||||
txp = self.txp
|
||||
uint160 = self.uint160
|
||||
self.assertEqual(uint160.size(), 20, "incorrect CBaseBlob::size")
|
||||
claim = CClaimValue(txp, uint160, 20, 1, 10)
|
||||
self.assertClaimEqual(claim, txp, uint160, 20, 20, 1, 10, "incorrect CClaimValue::CClaimValue")
|
||||
|
||||
def test_support(self):
|
||||
txp = self.txp
|
||||
uint160 = self.uint160
|
||||
claim = CClaimValue(txp, uint160, 20, 1, 10)
|
||||
support = CSupportValue(txp, uint160, 20, 1, 10)
|
||||
self.assertSupportEqual(support, claim.outPoint, claim.claimId, claim.nAmount, claim.nHeight, claim.nValidAtHeight, "incorrect CSupportValue::CSupportValue")
|
||||
|
||||
def test_claimtrie(self):
|
||||
txp = self.txp
|
||||
uint160 = self.uint160
|
||||
claim = CClaimValue(txp, uint160, 20, 0, 0)
|
||||
wipe = True; height = 1; data_dir = "."
|
||||
trie = CClaimTrie(10*1024*1024, wipe, height, data_dir)
|
||||
cache = CClaimTrieCache(trie)
|
||||
self.assertTrue(trie.empty(), "incorrect CClaimtrieCache::empty")
|
||||
self.assertTrue(cache.addClaim("test", txp, uint160, 20, 0, 0), "incorrect CClaimtrieCache::addClaim")
|
||||
self.assertTrue(cache.haveClaim("test", txp), "incorrect CClaimtrieCache::haveClaim")
|
||||
self.assertEqual(cache.getTotalNamesInTrie(), 1, "incorrect CClaimtrieCache::getTotalNamesInTrie")
|
||||
self.assertEqual(cache.getTotalClaimsInTrie(), 1, "incorrect CClaimtrieCache::getTotalClaimsInTrie")
|
||||
getNamesInTrie(cache, CacheIterateCallback(["test"]))
|
||||
nValidAtHeight = -1
|
||||
# add second claim
|
||||
txp.n = 2
|
||||
uint1601 = uint160S("1234567890987654321012345678909876543211")
|
||||
self.assertTrue(cache.addClaim("test", txp, uint1601, 20, 1, 1), "incorrect CClaimtrieCache::addClaim")
|
||||
result, nValidAtHeight = cache.haveClaimInQueue("test", txp)
|
||||
self.assertTrue(result, "incorrect CClaimTrieCache::haveClaimInQueue")
|
||||
self.assertEqual(nValidAtHeight, 1, "incorrect CClaimTrieCache::haveClaimInQueue, nValidAtHeight")
|
||||
claim1 = CClaimValue()
|
||||
self.assertTrue(cache.getInfoForName("test", claim1), "incorrect CClaimTrieCache::getInfoForName")
|
||||
self.assertEqual(claim, claim1, "incorrect CClaimtrieCache::getInfoForName")
|
||||
proof = CClaimTrieProof()
|
||||
self.assertTrue(cache.getProofForName("test", uint160, proof), "incorrect CacheProofCallback")
|
||||
self.assertTrue(proof.hasValue, "incorrect CClaimTrieCache::getProofForName")
|
||||
claimsToName = cache.getClaimsForName("test")
|
||||
claims = claimsToName.claimsNsupports
|
||||
self.assertEqual(claims.size(), 2, "incorrect CClaimTrieCache::getClaimsForName")
|
||||
self.assertFalse(claims[0].IsNull(), "incorrect CClaimNsupports::IsNull")
|
||||
self.assertFalse(claims[1].IsNull(), "incorrect CClaimNsupports::IsNull")
|
||||
|
||||
unittest.main()
|
||||
@@ -1,30 +0,0 @@
|
||||
|
||||
#include <log.h>
|
||||
|
||||
void CLogPrint::setLogger(ClogBase* log)
|
||||
{
|
||||
ss.str({});
|
||||
logger = log;
|
||||
}
|
||||
|
||||
CLogPrint& CLogPrint::global()
|
||||
{
|
||||
static CLogPrint logger;
|
||||
return logger;
|
||||
}
|
||||
|
||||
CLogPrint& CLogPrint::operator<<(const Clog& cl)
|
||||
{
|
||||
if (logger) {
|
||||
switch(cl) {
|
||||
case Clog::endl:
|
||||
ss << '\n';
|
||||
// fallthrough
|
||||
case Clog::flush:
|
||||
logger->LogPrintStr(ss.str());
|
||||
ss.str({});
|
||||
break;
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
|
||||
#ifndef CLAIMTRIE_LOG_H
|
||||
#define CLAIMTRIE_LOG_H
|
||||
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
|
||||
struct ClogBase
|
||||
{
|
||||
ClogBase() = default;
|
||||
virtual ~ClogBase() = default;
|
||||
virtual void LogPrintStr(const std::string&) = 0;
|
||||
};
|
||||
|
||||
enum struct Clog
|
||||
{
|
||||
endl = 0,
|
||||
flush = 1,
|
||||
};
|
||||
|
||||
struct CLogPrint
|
||||
{
|
||||
template <typename T>
|
||||
CLogPrint& operator<<(const T& a)
|
||||
{
|
||||
if (logger)
|
||||
ss << a;
|
||||
return *this;
|
||||
}
|
||||
|
||||
CLogPrint& operator<<(const Clog& cl);
|
||||
|
||||
void setLogger(ClogBase* log);
|
||||
static CLogPrint& global();
|
||||
|
||||
private:
|
||||
CLogPrint() = default;
|
||||
std::stringstream ss;
|
||||
ClogBase* logger = nullptr;
|
||||
};
|
||||
|
||||
#endif // CLAIMTRIE_LOG_H
|
||||
@@ -1,93 +0,0 @@
|
||||
|
||||
#ifndef SQLITE_H
|
||||
#define SQLITE_H
|
||||
|
||||
#include <sqlite/sqlite3.h>
|
||||
#include <uints.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
namespace sqlite
|
||||
{
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const uint160& val) {
|
||||
return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC);
|
||||
}
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const uint256& val) {
|
||||
return sqlite3_bind_blob(stmt, inx, val.begin(), int(val.size()), SQLITE_STATIC);
|
||||
}
|
||||
|
||||
inline void store_result_in_db(sqlite3_context* db, const uint160& val) {
|
||||
sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT);
|
||||
}
|
||||
|
||||
inline void store_result_in_db(sqlite3_context* db, const uint256& val) {
|
||||
sqlite3_result_blob(db, val.begin(), int(val.size()), SQLITE_TRANSIENT);
|
||||
}
|
||||
}
|
||||
|
||||
#include <sqlite/hdr/sqlite_modern_cpp.h>
|
||||
|
||||
namespace sqlite
|
||||
{
|
||||
template<>
|
||||
struct has_sqlite_type<uint256, SQLITE_BLOB, void> : std::true_type {};
|
||||
|
||||
template<>
|
||||
struct has_sqlite_type<uint160, SQLITE_BLOB, void> : std::true_type {};
|
||||
|
||||
inline uint160 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<uint160>) {
|
||||
uint160 ret;
|
||||
auto ptr = sqlite3_column_blob(stmt, inx);
|
||||
if (!ptr) return ret;
|
||||
int bytes = sqlite3_column_bytes(stmt, inx);
|
||||
assert(bytes > 0 && bytes <= int(ret.size()));
|
||||
std::memcpy(ret.begin(), ptr, bytes);
|
||||
return ret;
|
||||
}
|
||||
|
||||
inline uint256 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<uint256>) {
|
||||
uint256 ret;
|
||||
|
||||
// I think we need this, but I lost my specific test case:
|
||||
// auto type = sqlite3_column_type(stmt, inx);
|
||||
// if (type == SQLITE_NULL)
|
||||
// return ret;
|
||||
//
|
||||
// if (type == SQLITE_INTEGER) {
|
||||
// auto integer = sqlite3_column_int64(stmt, inx);
|
||||
// return uint256(integer);
|
||||
// }
|
||||
// assert(type == SQLITE_BLOB);
|
||||
|
||||
auto ptr = sqlite3_column_blob(stmt, inx);
|
||||
if (!ptr) return ret;
|
||||
int bytes = sqlite3_column_bytes(stmt, inx);
|
||||
assert(bytes <= ret.size());
|
||||
std::memcpy(ret.begin(), ptr, bytes);
|
||||
return ret;
|
||||
}
|
||||
|
||||
inline int commit(database& db, std::size_t attempts = 200)
|
||||
{
|
||||
int code = SQLITE_OK;
|
||||
for (auto i = 0u; i < attempts; ++i) {
|
||||
try {
|
||||
db << "COMMIT";
|
||||
} catch (const sqlite_exception& e) {
|
||||
code = e.get_code();
|
||||
if (code == SQLITE_LOCKED || code == SQLITE_BUSY) {
|
||||
using namespace std::chrono_literals;
|
||||
std::this_thread::sleep_for(100ms);
|
||||
continue;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
return SQLITE_OK;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // SQLITE_H
|
||||
@@ -1,682 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <tuple>
|
||||
#include <memory>
|
||||
|
||||
#define MODERN_SQLITE_VERSION 3002008
|
||||
|
||||
#include "../sqlite3.h"
|
||||
|
||||
#include "sqlite_modern_cpp/type_wrapper.h"
|
||||
#include "sqlite_modern_cpp/errors.h"
|
||||
#include "sqlite_modern_cpp/utility/function_traits.h"
|
||||
#include "sqlite_modern_cpp/utility/uncaught_exceptions.h"
|
||||
#include "sqlite_modern_cpp/utility/utf16_utf8.h"
|
||||
|
||||
namespace sqlite {
|
||||
|
||||
class database;
|
||||
class database_binder;
|
||||
|
||||
template<std::size_t> class binder;
|
||||
|
||||
typedef std::shared_ptr<sqlite3> connection_type;
|
||||
|
||||
template<class T, bool Name = false>
|
||||
struct index_binding_helper {
|
||||
index_binding_helper(const index_binding_helper &) = delete;
|
||||
#if __cplusplus < 201703
|
||||
index_binding_helper(index_binding_helper &&) = default;
|
||||
#endif
|
||||
typename std::conditional<Name, const char *, int>::type index;
|
||||
T value;
|
||||
};
|
||||
|
||||
template<class T>
|
||||
auto named_parameter(const char *name, T &&arg) {
|
||||
return index_binding_helper<decltype(arg), true>{name, std::forward<decltype(arg)>(arg)};
|
||||
}
|
||||
template<class T>
|
||||
auto indexed_parameter(int index, T &&arg) {
|
||||
return index_binding_helper<decltype(arg)>{index, std::forward<decltype(arg)>(arg)};
|
||||
}
|
||||
|
||||
class row_iterator;
|
||||
class database_binder {
|
||||
|
||||
public:
|
||||
// database_binder is not copyable
|
||||
database_binder() = delete;
|
||||
database_binder(const database_binder& other) = delete;
|
||||
database_binder& operator=(const database_binder&) = delete;
|
||||
|
||||
database_binder(database_binder&& other) :
|
||||
_db(std::move(other._db)),
|
||||
_stmt(std::move(other._stmt)),
|
||||
_inx(other._inx), execution_started(other.execution_started) { }
|
||||
|
||||
void execute();
|
||||
|
||||
std::string sql() {
|
||||
#if SQLITE_VERSION_NUMBER >= 3014000
|
||||
auto sqlite_deleter = [](void *ptr) {sqlite3_free(ptr);};
|
||||
std::unique_ptr<char, decltype(sqlite_deleter)> str(sqlite3_expanded_sql(_stmt.get()), sqlite_deleter);
|
||||
return str ? str.get() : original_sql();
|
||||
#else
|
||||
return original_sql();
|
||||
#endif
|
||||
}
|
||||
|
||||
std::string original_sql() {
|
||||
return sqlite3_sql(_stmt.get());
|
||||
}
|
||||
|
||||
void used(bool state) {
|
||||
if(!state) {
|
||||
// We may have to reset first if we haven't done so already:
|
||||
_next_index();
|
||||
--_inx;
|
||||
}
|
||||
execution_started = state;
|
||||
}
|
||||
bool used() const { return execution_started; }
|
||||
row_iterator begin();
|
||||
row_iterator end();
|
||||
|
||||
private:
|
||||
std::shared_ptr<sqlite3> _db;
|
||||
std::unique_ptr<sqlite3_stmt, decltype(&sqlite3_finalize)> _stmt;
|
||||
utility::UncaughtExceptionDetector _has_uncaught_exception;
|
||||
|
||||
int _inx;
|
||||
|
||||
bool execution_started = false;
|
||||
|
||||
int _next_index() {
|
||||
if(execution_started && !_inx) {
|
||||
sqlite3_reset(_stmt.get());
|
||||
sqlite3_clear_bindings(_stmt.get());
|
||||
}
|
||||
return ++_inx;
|
||||
}
|
||||
|
||||
sqlite3_stmt* _prepare(u16str_ref sql) {
|
||||
return _prepare(utility::utf16_to_utf8(sql));
|
||||
}
|
||||
|
||||
sqlite3_stmt* _prepare(str_ref sql) {
|
||||
int hresult;
|
||||
sqlite3_stmt* tmp = nullptr;
|
||||
const char *remaining;
|
||||
hresult = sqlite3_prepare_v2(_db.get(), sql.data(), sql.length(), &tmp, &remaining);
|
||||
if(hresult != SQLITE_OK) errors::throw_sqlite_error(hresult, sql, sqlite3_errmsg(_db.get()));
|
||||
if(!std::all_of(remaining, sql.data() + sql.size(), [](char ch) {return std::isspace(ch);}))
|
||||
throw errors::more_statements("Multiple semicolon separated statements are unsupported", sql);
|
||||
return tmp;
|
||||
}
|
||||
|
||||
template<typename T> friend database_binder& operator<<(database_binder& db, T&&);
|
||||
template<typename T> friend database_binder& operator<<(database_binder& db, index_binding_helper<T>);
|
||||
template<typename T> friend database_binder& operator<<(database_binder& db, index_binding_helper<T, true>);
|
||||
friend void operator++(database_binder& db, int);
|
||||
|
||||
public:
|
||||
|
||||
database_binder(std::shared_ptr<sqlite3> db, u16str_ref sql):
|
||||
_db(db),
|
||||
_stmt(_prepare(sql), sqlite3_finalize),
|
||||
_inx(0) {
|
||||
}
|
||||
|
||||
database_binder(std::shared_ptr<sqlite3> db, str_ref sql):
|
||||
_db(db),
|
||||
_stmt(_prepare(sql), sqlite3_finalize),
|
||||
_inx(0) {
|
||||
}
|
||||
|
||||
~database_binder() noexcept(false) {
|
||||
/* Will be executed if no >>op is found, but not if an exception
|
||||
is in mid flight */
|
||||
if(!used() && !_has_uncaught_exception && _stmt) {
|
||||
execute();
|
||||
}
|
||||
}
|
||||
|
||||
friend class row_iterator;
|
||||
};
|
||||
|
||||
class row_iterator {
|
||||
public:
|
||||
class value_type {
|
||||
public:
|
||||
value_type(database_binder *_binder): _binder(_binder) {};
|
||||
template<class T>
|
||||
typename std::enable_if<is_sqlite_value<T>::value, value_type &>::type operator >>(T &result) {
|
||||
result = get_col_from_db(_binder->_stmt.get(), next_index++, result_type<T>());
|
||||
return *this;
|
||||
}
|
||||
template<class ...Types>
|
||||
value_type &operator >>(std::tuple<Types...>& values) {
|
||||
values = handle_tuple<std::tuple<typename std::decay<Types>::type...>>(std::index_sequence_for<Types...>());
|
||||
next_index += sizeof...(Types);
|
||||
return *this;
|
||||
}
|
||||
template<class ...Types>
|
||||
value_type &operator >>(std::tuple<Types...>&& values) {
|
||||
return *this >> values;
|
||||
}
|
||||
template<class ...Types>
|
||||
operator std::tuple<Types...>() {
|
||||
std::tuple<Types...> value;
|
||||
*this >> value;
|
||||
return value;
|
||||
}
|
||||
explicit operator bool() {
|
||||
return sqlite3_column_count(_binder->_stmt.get()) >= next_index;
|
||||
}
|
||||
int& index() { return next_index; }
|
||||
private:
|
||||
template<class Tuple, std::size_t ...Index>
|
||||
Tuple handle_tuple(std::index_sequence<Index...>) {
|
||||
return Tuple(
|
||||
get_col_from_db(
|
||||
_binder->_stmt.get(),
|
||||
next_index + Index,
|
||||
result_type<typename std::tuple_element<Index, Tuple>::type>())...);
|
||||
}
|
||||
database_binder *_binder;
|
||||
int next_index = 0;
|
||||
};
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using pointer = value_type*;
|
||||
using reference = value_type&;
|
||||
using iterator_category = std::input_iterator_tag;
|
||||
|
||||
row_iterator() = default;
|
||||
explicit row_iterator(database_binder &binder): _binder(&binder) {
|
||||
_binder->_next_index();
|
||||
_binder->_inx = 0;
|
||||
_binder->used(true);
|
||||
++*this;
|
||||
}
|
||||
|
||||
reference operator*() const { return value;}
|
||||
pointer operator->() const { return std::addressof(**this); }
|
||||
row_iterator &operator++() {
|
||||
switch(int result = sqlite3_step(_binder->_stmt.get())) {
|
||||
case SQLITE_ROW:
|
||||
value = {_binder};
|
||||
break;
|
||||
case SQLITE_DONE:
|
||||
_binder = nullptr;
|
||||
break;
|
||||
default:
|
||||
exceptions::throw_sqlite_error(result, _binder->sql(), sqlite3_errmsg(_binder->_db.get()));
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline bool operator ==(const row_iterator &a, const row_iterator &b) {
|
||||
return a._binder == b._binder;
|
||||
}
|
||||
friend inline bool operator !=(const row_iterator &a, const row_iterator &b) {
|
||||
return !(a==b);
|
||||
}
|
||||
|
||||
private:
|
||||
database_binder *_binder = nullptr;
|
||||
mutable value_type value{_binder}; // mutable, because `changing` the value is just reading it
|
||||
};
|
||||
|
||||
inline row_iterator database_binder::begin() {
|
||||
return row_iterator(*this);
|
||||
}
|
||||
|
||||
inline row_iterator database_binder::end() {
|
||||
return row_iterator();
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
template<class Callback>
|
||||
void _extract_single_value(database_binder &binder, Callback call_back) {
|
||||
auto iter = binder.begin();
|
||||
if(iter == binder.end())
|
||||
throw errors::no_rows("no rows to extract: exactly 1 row expected", binder.sql(), SQLITE_DONE);
|
||||
|
||||
call_back(*iter);
|
||||
|
||||
if(++iter != binder.end())
|
||||
throw errors::more_rows("not all rows extracted", binder.sql(), SQLITE_ROW);
|
||||
}
|
||||
}
|
||||
inline void database_binder::execute() {
|
||||
for(auto &&row : *this)
|
||||
(void)row;
|
||||
}
|
||||
namespace detail {
|
||||
template<class T> using void_t = void;
|
||||
template<class T, class = void>
|
||||
struct sqlite_direct_result : std::false_type {};
|
||||
template<class T>
|
||||
struct sqlite_direct_result<
|
||||
T,
|
||||
void_t<decltype(std::declval<row_iterator::value_type&>() >> std::declval<T&&>())>
|
||||
> : std::true_type {};
|
||||
}
|
||||
template <typename Result>
|
||||
inline typename std::enable_if<detail::sqlite_direct_result<Result>::value>::type operator>>(database_binder &binder, Result&& value) {
|
||||
detail::_extract_single_value(binder, [&value] (row_iterator::value_type &row) {
|
||||
row >> std::forward<Result>(value);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Function>
|
||||
inline typename std::enable_if<!detail::sqlite_direct_result<Function>::value>::type operator>>(database_binder &db_binder, Function&& func) {
|
||||
using traits = utility::function_traits<Function>;
|
||||
|
||||
for(auto &&row : db_binder) {
|
||||
binder<traits::arity>::run(row, func);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Result>
|
||||
inline decltype(auto) operator>>(database_binder &&binder, Result&& value) {
|
||||
return binder >> std::forward<Result>(value);
|
||||
}
|
||||
|
||||
namespace sql_function_binder {
|
||||
template<
|
||||
typename ContextType,
|
||||
std::size_t Count,
|
||||
typename Functions
|
||||
>
|
||||
inline void step(
|
||||
sqlite3_context* db,
|
||||
int count,
|
||||
sqlite3_value** vals
|
||||
);
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Functions,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) && sizeof...(Values) < Count), void>::type step(
|
||||
sqlite3_context* db,
|
||||
int count,
|
||||
sqlite3_value** vals,
|
||||
Values&&... values
|
||||
);
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Functions,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) == Count), void>::type step(
|
||||
sqlite3_context* db,
|
||||
int,
|
||||
sqlite3_value**,
|
||||
Values&&... values
|
||||
);
|
||||
|
||||
template<
|
||||
typename ContextType,
|
||||
typename Functions
|
||||
>
|
||||
inline void final(sqlite3_context* db);
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Function,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) < Count), void>::type scalar(
|
||||
sqlite3_context* db,
|
||||
int count,
|
||||
sqlite3_value** vals,
|
||||
Values&&... values
|
||||
);
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Function,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) == Count), void>::type scalar(
|
||||
sqlite3_context* db,
|
||||
int,
|
||||
sqlite3_value**,
|
||||
Values&&... values
|
||||
);
|
||||
}
|
||||
|
||||
enum class OpenFlags {
|
||||
READONLY = SQLITE_OPEN_READONLY,
|
||||
READWRITE = SQLITE_OPEN_READWRITE,
|
||||
CREATE = SQLITE_OPEN_CREATE,
|
||||
NOMUTEX = SQLITE_OPEN_NOMUTEX,
|
||||
FULLMUTEX = SQLITE_OPEN_FULLMUTEX,
|
||||
SHAREDCACHE = SQLITE_OPEN_SHAREDCACHE,
|
||||
PRIVATECACH = SQLITE_OPEN_PRIVATECACHE,
|
||||
URI = SQLITE_OPEN_URI
|
||||
};
|
||||
inline OpenFlags operator|(const OpenFlags& a, const OpenFlags& b) {
|
||||
return static_cast<OpenFlags>(static_cast<int>(a) | static_cast<int>(b));
|
||||
}
|
||||
enum class Encoding {
|
||||
ANY = SQLITE_ANY,
|
||||
UTF8 = SQLITE_UTF8,
|
||||
UTF16 = SQLITE_UTF16
|
||||
};
|
||||
struct sqlite_config {
|
||||
OpenFlags flags = OpenFlags::READWRITE | OpenFlags::CREATE;
|
||||
const char *zVfs = nullptr;
|
||||
Encoding encoding = Encoding::ANY;
|
||||
};
|
||||
|
||||
class database {
|
||||
protected:
|
||||
std::shared_ptr<sqlite3> _db;
|
||||
|
||||
public:
|
||||
database(const std::string &db_name, const sqlite_config &config = {}): _db(nullptr) {
|
||||
sqlite3* tmp = nullptr;
|
||||
auto ret = sqlite3_open_v2(db_name.data(), &tmp, static_cast<int>(config.flags), config.zVfs);
|
||||
_db = std::shared_ptr<sqlite3>(tmp, [=](sqlite3* ptr) { sqlite3_close_v2(ptr); }); // this will close the connection eventually when no longer needed.
|
||||
if(ret != SQLITE_OK) errors::throw_sqlite_error(_db ? sqlite3_extended_errcode(_db.get()) : ret, {}, sqlite3_errmsg(_db.get()));
|
||||
sqlite3_extended_result_codes(_db.get(), true);
|
||||
if(config.encoding == Encoding::UTF16)
|
||||
*this << R"(PRAGMA encoding = "UTF-16";)";
|
||||
}
|
||||
|
||||
database(const std::u16string &db_name, const sqlite_config &config = {}): database(utility::utf16_to_utf8(db_name), config) {
|
||||
if (config.encoding == Encoding::ANY)
|
||||
*this << R"(PRAGMA encoding = "UTF-16";)";
|
||||
}
|
||||
|
||||
database(std::shared_ptr<sqlite3> db):
|
||||
_db(db) {}
|
||||
|
||||
database_binder operator<<(str_ref sql) {
|
||||
return database_binder(_db, sql);
|
||||
}
|
||||
|
||||
database_binder operator<<(u16str_ref sql) {
|
||||
return database_binder(_db, sql);
|
||||
}
|
||||
|
||||
connection_type connection() const { return _db; }
|
||||
|
||||
sqlite3_int64 last_insert_rowid() const {
|
||||
return sqlite3_last_insert_rowid(_db.get());
|
||||
}
|
||||
|
||||
int rows_modified() const {
|
||||
return sqlite3_changes(_db.get());
|
||||
}
|
||||
|
||||
template <typename Function>
|
||||
void define(const std::string &name, Function&& func, bool deterministic = true) {
|
||||
typedef utility::function_traits<Function> traits;
|
||||
|
||||
auto funcPtr = new auto(std::forward<Function>(func));
|
||||
if(int result = sqlite3_create_function_v2(
|
||||
_db.get(), name.data(), traits::arity, SQLITE_UTF8 | (deterministic ? SQLITE_DETERMINISTIC : 0), funcPtr,
|
||||
sql_function_binder::scalar<traits::arity, typename std::remove_reference<Function>::type>,
|
||||
nullptr, nullptr, [](void* ptr){
|
||||
delete static_cast<decltype(funcPtr)>(ptr);
|
||||
}))
|
||||
errors::throw_sqlite_error(result, {}, sqlite3_errmsg(_db.get()));
|
||||
}
|
||||
|
||||
template <typename StepFunction, typename FinalFunction>
|
||||
void define(const std::string &name, StepFunction&& step, FinalFunction&& final, bool deterministic = true) {
|
||||
typedef utility::function_traits<StepFunction> traits;
|
||||
using ContextType = typename std::remove_reference<typename traits::template argument<0>>::type;
|
||||
|
||||
auto funcPtr = new auto(std::make_pair(std::forward<StepFunction>(step), std::forward<FinalFunction>(final)));
|
||||
if(int result = sqlite3_create_function_v2(
|
||||
_db.get(), name.c_str(), traits::arity - 1, SQLITE_UTF8 | (deterministic ? SQLITE_DETERMINISTIC : 0), funcPtr, nullptr,
|
||||
sql_function_binder::step<ContextType, traits::arity, typename std::remove_reference<decltype(*funcPtr)>::type>,
|
||||
sql_function_binder::final<ContextType, typename std::remove_reference<decltype(*funcPtr)>::type>,
|
||||
[](void* ptr){
|
||||
delete static_cast<decltype(funcPtr)>(ptr);
|
||||
}))
|
||||
errors::throw_sqlite_error(result, {}, sqlite3_errmsg(_db.get()));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
template<std::size_t Count>
|
||||
class binder {
|
||||
private:
|
||||
template <
|
||||
typename Function,
|
||||
std::size_t Index
|
||||
>
|
||||
using nth_argument_type = typename utility::function_traits<
|
||||
Function
|
||||
>::template argument<Index>;
|
||||
|
||||
public:
|
||||
// `Boundary` needs to be defaulted to `Count` so that the `run` function
|
||||
// template is not implicitly instantiated on class template instantiation.
|
||||
// Look up section 14.7.1 _Implicit instantiation_ of the ISO C++14 Standard
|
||||
// and the [dicussion](https://github.com/aminroosta/sqlite_modern_cpp/issues/8)
|
||||
// on Github.
|
||||
|
||||
template<
|
||||
typename Function,
|
||||
typename... Values,
|
||||
std::size_t Boundary = Count
|
||||
>
|
||||
static typename std::enable_if<(sizeof...(Values) < Boundary), void>::type run(
|
||||
row_iterator::value_type& row,
|
||||
Function&& function,
|
||||
Values&&... values
|
||||
) {
|
||||
typename std::decay<nth_argument_type<Function, sizeof...(Values)>>::type value;
|
||||
row >> value;
|
||||
run<Function>(row, function, std::forward<Values>(values)..., std::move(value));
|
||||
}
|
||||
|
||||
template<
|
||||
typename Function,
|
||||
typename... Values,
|
||||
std::size_t Boundary = Count
|
||||
>
|
||||
static typename std::enable_if<(sizeof...(Values) == Boundary), void>::type run(
|
||||
row_iterator::value_type&,
|
||||
Function&& function,
|
||||
Values&&... values
|
||||
) {
|
||||
function(std::move(values)...);
|
||||
}
|
||||
};
|
||||
|
||||
// Some ppl are lazy so we have a operator for proper prep. statemant handling.
|
||||
void inline operator++(database_binder& db, int) { db.execute(); }
|
||||
|
||||
template<typename T> database_binder &operator<<(database_binder& db, index_binding_helper<T> val) {
|
||||
db._next_index(); --db._inx;
|
||||
int result = bind_col_in_db(db._stmt.get(), val.index, std::forward<T>(val.value));
|
||||
if(result != SQLITE_OK)
|
||||
exceptions::throw_sqlite_error(result, db.sql(), sqlite3_errmsg(db._db.get()));
|
||||
return db;
|
||||
}
|
||||
|
||||
template<typename T> database_binder &operator<<(database_binder& db, index_binding_helper<T, true> val) {
|
||||
db._next_index(); --db._inx;
|
||||
int index = sqlite3_bind_parameter_index(db._stmt.get(), val.index);
|
||||
if(!index)
|
||||
throw errors::unknown_binding("The given binding name is not valid for this statement", db.sql());
|
||||
int result = bind_col_in_db(db._stmt.get(), index, std::forward<T>(val.value));
|
||||
if(result != SQLITE_OK)
|
||||
exceptions::throw_sqlite_error(result, db.sql(), sqlite3_errmsg(db._db.get()));
|
||||
return db;
|
||||
}
|
||||
|
||||
template<typename T> database_binder &operator<<(database_binder& db, T&& val) {
|
||||
int result = bind_col_in_db(db._stmt.get(), db._next_index(), std::forward<T>(val));
|
||||
if(result != SQLITE_OK)
|
||||
exceptions::throw_sqlite_error(result, db.sql(), sqlite3_errmsg(db._db.get()));
|
||||
return db;
|
||||
}
|
||||
// Convert the rValue binder to a reference and call first op<<, its needed for the call that creates the binder (be carefull of recursion here!)
|
||||
template<typename T> database_binder operator << (database_binder&& db, const T& val) { db << val; return std::move(db); }
|
||||
template<typename T, bool Name> database_binder operator << (database_binder&& db, index_binding_helper<T, Name> val) { db << index_binding_helper<T, Name>{val.index, std::forward<T>(val.value)}; return std::move(db); }
|
||||
|
||||
namespace sql_function_binder {
|
||||
template<class T>
|
||||
struct AggregateCtxt {
|
||||
T obj;
|
||||
bool constructed = true;
|
||||
};
|
||||
|
||||
template<
|
||||
typename ContextType,
|
||||
std::size_t Count,
|
||||
typename Functions
|
||||
>
|
||||
inline void step(
|
||||
sqlite3_context* db,
|
||||
int count,
|
||||
sqlite3_value** vals
|
||||
) {
|
||||
auto ctxt = static_cast<AggregateCtxt<ContextType>*>(sqlite3_aggregate_context(db, sizeof(AggregateCtxt<ContextType>)));
|
||||
if(!ctxt) return;
|
||||
try {
|
||||
if(!ctxt->constructed) new(ctxt) AggregateCtxt<ContextType>();
|
||||
step<Count, Functions>(db, count, vals, ctxt->obj);
|
||||
return;
|
||||
} catch(const sqlite_exception &e) {
|
||||
sqlite3_result_error_code(db, e.get_code());
|
||||
sqlite3_result_error(db, e.what(), -1);
|
||||
} catch(const std::exception &e) {
|
||||
sqlite3_result_error(db, e.what(), -1);
|
||||
} catch(...) {
|
||||
sqlite3_result_error(db, "Unknown error", -1);
|
||||
}
|
||||
if(ctxt && ctxt->constructed)
|
||||
ctxt->~AggregateCtxt();
|
||||
}
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Functions,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) && sizeof...(Values) < Count), void>::type step(
|
||||
sqlite3_context* db,
|
||||
int count,
|
||||
sqlite3_value** vals,
|
||||
Values&&... values
|
||||
) {
|
||||
using arg_type = typename std::remove_cv<
|
||||
typename std::remove_reference<
|
||||
typename utility::function_traits<
|
||||
typename Functions::first_type
|
||||
>::template argument<sizeof...(Values)>
|
||||
>::type
|
||||
>::type;
|
||||
|
||||
step<Count, Functions>(
|
||||
db,
|
||||
count,
|
||||
vals,
|
||||
std::forward<Values>(values)...,
|
||||
get_val_from_db(vals[sizeof...(Values) - 1], result_type<arg_type>()));
|
||||
}
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Functions,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) == Count), void>::type step(
|
||||
sqlite3_context* db,
|
||||
int,
|
||||
sqlite3_value**,
|
||||
Values&&... values
|
||||
) {
|
||||
static_cast<Functions*>(sqlite3_user_data(db))->first(std::forward<Values>(values)...);
|
||||
}
|
||||
|
||||
template<
|
||||
typename ContextType,
|
||||
typename Functions
|
||||
>
|
||||
inline void final(sqlite3_context* db) {
|
||||
auto ctxt = static_cast<AggregateCtxt<ContextType>*>(sqlite3_aggregate_context(db, sizeof(AggregateCtxt<ContextType>)));
|
||||
try {
|
||||
if(!ctxt) return;
|
||||
if(!ctxt->constructed) new(ctxt) AggregateCtxt<ContextType>();
|
||||
store_result_in_db(db,
|
||||
static_cast<Functions*>(sqlite3_user_data(db))->second(ctxt->obj));
|
||||
} catch(const sqlite_exception &e) {
|
||||
sqlite3_result_error_code(db, e.get_code());
|
||||
sqlite3_result_error(db, e.what(), -1);
|
||||
} catch(const std::exception &e) {
|
||||
sqlite3_result_error(db, e.what(), -1);
|
||||
} catch(...) {
|
||||
sqlite3_result_error(db, "Unknown error", -1);
|
||||
}
|
||||
if(ctxt && ctxt->constructed)
|
||||
ctxt->~AggregateCtxt();
|
||||
}
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Function,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) < Count), void>::type scalar(
|
||||
sqlite3_context* db,
|
||||
int count,
|
||||
sqlite3_value** vals,
|
||||
Values&&... values
|
||||
) {
|
||||
using arg_type = typename std::remove_cv<
|
||||
typename std::remove_reference<
|
||||
typename utility::function_traits<Function>::template argument<sizeof...(Values)>
|
||||
>::type
|
||||
>::type;
|
||||
|
||||
scalar<Count, Function>(
|
||||
db,
|
||||
count,
|
||||
vals,
|
||||
std::forward<Values>(values)...,
|
||||
get_val_from_db(vals[sizeof...(Values)], result_type<arg_type>()));
|
||||
}
|
||||
|
||||
template<
|
||||
std::size_t Count,
|
||||
typename Function,
|
||||
typename... Values
|
||||
>
|
||||
inline typename std::enable_if<(sizeof...(Values) == Count), void>::type scalar(
|
||||
sqlite3_context* db,
|
||||
int,
|
||||
sqlite3_value**,
|
||||
Values&&... values
|
||||
) {
|
||||
try {
|
||||
store_result_in_db(db,
|
||||
(*static_cast<Function*>(sqlite3_user_data(db)))(std::forward<Values>(values)...));
|
||||
} catch(const sqlite_exception &e) {
|
||||
sqlite3_result_error_code(db, e.get_code());
|
||||
sqlite3_result_error(db, e.what(), -1);
|
||||
} catch(const std::exception &e) {
|
||||
sqlite3_result_error(db, e.what(), -1);
|
||||
} catch(...) {
|
||||
sqlite3_result_error(db, "Unknown error", -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "../../sqlite3.h"
|
||||
|
||||
namespace sqlite {
|
||||
|
||||
class sqlite_exception: public std::runtime_error {
|
||||
public:
|
||||
sqlite_exception(const char* msg, str_ref sql, int code = -1): runtime_error(msg + std::string(": ") + sql), code(code), sql(sql) {}
|
||||
sqlite_exception(int code, str_ref sql, const char *msg = nullptr): runtime_error((msg ? msg : sqlite3_errstr(code)) + std::string(": ") + sql), code(code), sql(sql) {}
|
||||
int get_code() const {return code & 0xFF;}
|
||||
int get_extended_code() const {return code;}
|
||||
std::string get_sql() const {return sql;}
|
||||
const char *errstr() const {return code == -1 ? "Unknown error" : sqlite3_errstr(code);}
|
||||
private:
|
||||
int code;
|
||||
std::string sql;
|
||||
};
|
||||
|
||||
namespace errors {
|
||||
//One more or less trivial derived error class for each SQLITE error.
|
||||
//Note the following are not errors so have no classes:
|
||||
//SQLITE_OK, SQLITE_NOTICE, SQLITE_WARNING, SQLITE_ROW, SQLITE_DONE
|
||||
//
|
||||
//Note these names are exact matches to the names of the SQLITE error codes.
|
||||
#define SQLITE_MODERN_CPP_ERROR_CODE(NAME,name,derived) \
|
||||
class name: public sqlite_exception { using sqlite_exception::sqlite_exception; };\
|
||||
derived
|
||||
#define SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(BASE,SUB,base,sub) \
|
||||
class base ## _ ## sub: public base { using base::base; };
|
||||
#include "lists/error_codes.h"
|
||||
#undef SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED
|
||||
#undef SQLITE_MODERN_CPP_ERROR_CODE
|
||||
|
||||
//Some additional errors are here for the C++ interface
|
||||
class more_rows: public sqlite_exception { using sqlite_exception::sqlite_exception; };
|
||||
class no_rows: public sqlite_exception { using sqlite_exception::sqlite_exception; };
|
||||
class more_statements: public sqlite_exception { using sqlite_exception::sqlite_exception; }; // Prepared statements can only contain one statement
|
||||
class invalid_utf16: public sqlite_exception { using sqlite_exception::sqlite_exception; };
|
||||
class unknown_binding: public sqlite_exception { using sqlite_exception::sqlite_exception; };
|
||||
|
||||
static void throw_sqlite_error(const int& error_code, str_ref sql = "", const char *errmsg = nullptr) {
|
||||
switch(error_code & 0xFF) {
|
||||
#define SQLITE_MODERN_CPP_ERROR_CODE(NAME,name,derived) \
|
||||
case SQLITE_ ## NAME: switch(error_code) { \
|
||||
derived \
|
||||
case SQLITE_ ## NAME: \
|
||||
default: throw name(error_code, sql); \
|
||||
}
|
||||
|
||||
#if SQLITE_VERSION_NUMBER < 3010000
|
||||
#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
|
||||
#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
|
||||
#define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
|
||||
#endif
|
||||
|
||||
#define SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(BASE,SUB,base,sub) \
|
||||
case SQLITE_ ## BASE ## _ ## SUB: throw base ## _ ## sub(error_code, sql, errmsg);
|
||||
#include "lists/error_codes.h"
|
||||
#undef SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED
|
||||
#undef SQLITE_MODERN_CPP_ERROR_CODE
|
||||
default: throw sqlite_exception(error_code, sql, errmsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace exceptions = errors;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(ERROR,error,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(INTERNAL,internal,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(PERM,perm,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(ABORT,abort,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(ABORT,ROLLBACK,abort,rollback)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(BUSY,busy,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(BUSY,RECOVERY,busy,recovery)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(BUSY,SNAPSHOT,busy,snapshot)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(LOCKED,locked,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(LOCKED,SHAREDCACHE,locked,sharedcache)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(NOMEM,nomem,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(READONLY,readonly,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(INTERRUPT,interrupt,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(IOERR,ioerr,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,READ,ioerr,read)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,SHORT_READ,ioerr,short_read)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,WRITE,ioerr,write)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,FSYNC,ioerr,fsync)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,DIR_FSYNC,ioerr,dir_fsync)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,TRUNCATE,ioerr,truncate)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,FSTAT,ioerr,fstat)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,UNLOCK,ioerr,unlock)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,RDLOCK,ioerr,rdlock)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,DELETE,ioerr,delete)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,BLOCKED,ioerr,blocked)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,NOMEM,ioerr,nomem)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,ACCESS,ioerr,access)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,CHECKRESERVEDLOCK,ioerr,checkreservedlock)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,LOCK,ioerr,lock)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,CLOSE,ioerr,close)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,DIR_CLOSE,ioerr,dir_close)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,SHMOPEN,ioerr,shmopen)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,SHMSIZE,ioerr,shmsize)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,SHMLOCK,ioerr,shmlock)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,SHMMAP,ioerr,shmmap)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,SEEK,ioerr,seek)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,DELETE_NOENT,ioerr,delete_noent)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,MMAP,ioerr,mmap)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,GETTEMPPATH,ioerr,gettemppath)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,CONVPATH,ioerr,convpath)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,VNODE,ioerr,vnode)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(IOERR,AUTH,ioerr,auth)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(CORRUPT,corrupt,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CORRUPT,VTAB,corrupt,vtab)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(NOTFOUND,notfound,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(FULL,full,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(CANTOPEN,cantopen,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CANTOPEN,NOTEMPDIR,cantopen,notempdir)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CANTOPEN,ISDIR,cantopen,isdir)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CANTOPEN,FULLPATH,cantopen,fullpath)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CANTOPEN,CONVPATH,cantopen,convpath)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(PROTOCOL,protocol,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(EMPTY,empty,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(SCHEMA,schema,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(TOOBIG,toobig,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(CONSTRAINT,constraint,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,CHECK,constraint,check)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,COMMITHOOK,constraint,commithook)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,FOREIGNKEY,constraint,foreignkey)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,FUNCTION,constraint,function)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,NOTNULL,constraint,notnull)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,PRIMARYKEY,constraint,primarykey)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,TRIGGER,constraint,trigger)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,UNIQUE,constraint,unique)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,VTAB,constraint,vtab)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(CONSTRAINT,ROWID,constraint,rowid)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(MISMATCH,mismatch,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(MISUSE,misuse,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(NOLFS,nolfs,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(AUTH,auth,
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(FORMAT,format,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(RANGE,range,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(NOTADB,notadb,)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(NOTICE,notice,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(NOTICE,RECOVER_WAL,notice,recover_wal)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(NOTICE,RECOVER_ROLLBACK,notice,recover_rollback)
|
||||
)
|
||||
SQLITE_MODERN_CPP_ERROR_CODE(WARNING,warning,
|
||||
SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(WARNING,AUTOINDEX,warning,autoindex)
|
||||
)
|
||||
@@ -1,101 +0,0 @@
|
||||
#include "errors.h"
|
||||
|
||||
#include <sqlite/sqlite3.h>
|
||||
|
||||
#include <utility>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
|
||||
namespace sqlite {
|
||||
namespace detail {
|
||||
template<class>
|
||||
using void_t = void;
|
||||
template<class T, class = void>
|
||||
struct is_callable : std::false_type {};
|
||||
template<class Functor, class ...Arguments>
|
||||
struct is_callable<Functor(Arguments...), void_t<decltype(std::declval<Functor>()(std::declval<Arguments>()...))>> : std::true_type {};
|
||||
template<class Functor, class ...Functors>
|
||||
class FunctorOverload: public Functor, public FunctorOverload<Functors...> {
|
||||
public:
|
||||
template<class Functor1, class ...Remaining>
|
||||
FunctorOverload(Functor1 &&functor, Remaining &&... remaining):
|
||||
Functor(std::forward<Functor1>(functor)),
|
||||
FunctorOverload<Functors...>(std::forward<Remaining>(remaining)...) {}
|
||||
using Functor::operator();
|
||||
using FunctorOverload<Functors...>::operator();
|
||||
};
|
||||
template<class Functor>
|
||||
class FunctorOverload<Functor>: public Functor {
|
||||
public:
|
||||
template<class Functor1>
|
||||
FunctorOverload(Functor1 &&functor):
|
||||
Functor(std::forward<Functor1>(functor)) {}
|
||||
using Functor::operator();
|
||||
};
|
||||
template<class Functor>
|
||||
class WrapIntoFunctor: public Functor {
|
||||
public:
|
||||
template<class Functor1>
|
||||
WrapIntoFunctor(Functor1 &&functor):
|
||||
Functor(std::forward<Functor1>(functor)) {}
|
||||
using Functor::operator();
|
||||
};
|
||||
template<class ReturnType, class ...Arguments>
|
||||
class WrapIntoFunctor<ReturnType(*)(Arguments...)> {
|
||||
ReturnType(*ptr)(Arguments...);
|
||||
public:
|
||||
WrapIntoFunctor(ReturnType(*ptr)(Arguments...)): ptr(ptr) {}
|
||||
ReturnType operator()(Arguments... arguments) { return (*ptr)(std::forward<Arguments>(arguments)...); }
|
||||
};
|
||||
inline void store_error_log_data_pointer(std::shared_ptr<void> ptr) {
|
||||
static std::shared_ptr<void> stored;
|
||||
stored = std::move(ptr);
|
||||
}
|
||||
template<class T>
|
||||
std::shared_ptr<typename std::decay<T>::type> make_shared_inferred(T &&t) {
|
||||
return std::make_shared<typename std::decay<T>::type>(std::forward<T>(t));
|
||||
}
|
||||
}
|
||||
template<class Handler>
|
||||
typename std::enable_if<!detail::is_callable<Handler(const sqlite_exception&)>::value>::type
|
||||
error_log(Handler &&handler);
|
||||
template<class Handler>
|
||||
typename std::enable_if<detail::is_callable<Handler(const sqlite_exception&)>::value>::type
|
||||
error_log(Handler &&handler);
|
||||
template<class ...Handler>
|
||||
typename std::enable_if<sizeof...(Handler)>=2>::type
|
||||
error_log(Handler &&...handler) {
|
||||
return error_log(detail::FunctorOverload<detail::WrapIntoFunctor<typename std::decay<Handler>::type>...>(std::forward<Handler>(handler)...));
|
||||
}
|
||||
template<class Handler>
|
||||
typename std::enable_if<!detail::is_callable<Handler(const sqlite_exception&)>::value>::type
|
||||
error_log(Handler &&handler) {
|
||||
return error_log(std::forward<Handler>(handler), [](const sqlite_exception&) {});
|
||||
}
|
||||
template<class Handler>
|
||||
typename std::enable_if<detail::is_callable<Handler(const sqlite_exception&)>::value>::type
|
||||
error_log(Handler &&handler) {
|
||||
auto ptr = detail::make_shared_inferred([handler = std::forward<Handler>(handler)](int error_code, const char *errstr) mutable {
|
||||
switch(error_code & 0xFF) {
|
||||
#define SQLITE_MODERN_CPP_ERROR_CODE(NAME,name,derived) \
|
||||
case SQLITE_ ## NAME: switch(error_code) { \
|
||||
derived \
|
||||
default: handler(errors::name(errstr, "", error_code)); \
|
||||
};break;
|
||||
#define SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED(BASE,SUB,base,sub) \
|
||||
case SQLITE_ ## BASE ## _ ## SUB: \
|
||||
handler(errors::base ## _ ## sub(errstr, "", error_code)); \
|
||||
break;
|
||||
#include "lists/error_codes.h"
|
||||
#undef SQLITE_MODERN_CPP_ERROR_CODE_EXTENDED
|
||||
#undef SQLITE_MODERN_CPP_ERROR_CODE
|
||||
default: handler(sqlite_exception(errstr, "", error_code)); \
|
||||
}
|
||||
});
|
||||
|
||||
sqlite3_config(SQLITE_CONFIG_LOG, static_cast<void(*)(void*,int,const char*)>([](void *functor, int error_code, const char *errstr) {
|
||||
(*static_cast<decltype(ptr.get())>(functor))(error_code, errstr);
|
||||
}), ptr.get());
|
||||
detail::store_error_log_data_pointer(std::move(ptr));
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#ifndef SQLITE_HAS_CODEC
|
||||
#define SQLITE_HAS_CODEC
|
||||
#endif
|
||||
|
||||
#include "../sqlite_modern_cpp.h"
|
||||
|
||||
namespace sqlite {
|
||||
struct sqlcipher_config : public sqlite_config {
|
||||
std::string key;
|
||||
};
|
||||
|
||||
class sqlcipher_database : public database {
|
||||
public:
|
||||
sqlcipher_database(std::string db, const sqlcipher_config &config): database(db, config) {
|
||||
set_key(config.key);
|
||||
}
|
||||
|
||||
sqlcipher_database(std::u16string db, const sqlcipher_config &config): database(db, config) {
|
||||
set_key(config.key);
|
||||
}
|
||||
|
||||
void set_key(const std::string &key) {
|
||||
if(auto ret = sqlite3_key(_db.get(), key.data(), key.size()))
|
||||
errors::throw_sqlite_error(ret);
|
||||
}
|
||||
|
||||
void set_key(const std::string &key, const std::string &db_name) {
|
||||
if(auto ret = sqlite3_key_v2(_db.get(), db_name.c_str(), key.data(), key.size()))
|
||||
errors::throw_sqlite_error(ret);
|
||||
}
|
||||
|
||||
void rekey(const std::string &new_key) {
|
||||
if(auto ret = sqlite3_rekey(_db.get(), new_key.data(), new_key.size()))
|
||||
errors::throw_sqlite_error(ret);
|
||||
}
|
||||
|
||||
void rekey(const std::string &new_key, const std::string &db_name) {
|
||||
if(auto ret = sqlite3_rekey_v2(_db.get(), db_name.c_str(), new_key.data(), new_key.size()))
|
||||
errors::throw_sqlite_error(ret);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,412 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <type_traits>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#ifdef __has_include
|
||||
#if __cplusplus >= 201703 && __has_include(<string_view>)
|
||||
#define MODERN_SQLITE_STRINGVIEW_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
#ifdef __has_include
|
||||
#if __cplusplus > 201402 && __has_include(<optional>)
|
||||
#define MODERN_SQLITE_STD_OPTIONAL_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __has_include
|
||||
#if __cplusplus > 201402 && __has_include(<variant>)
|
||||
#define MODERN_SQLITE_STD_VARIANT_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef MODERN_SQLITE_STD_OPTIONAL_SUPPORT
|
||||
#include <optional>
|
||||
#endif
|
||||
|
||||
#ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT
|
||||
#include <variant>
|
||||
#endif
|
||||
#ifdef MODERN_SQLITE_STRINGVIEW_SUPPORT
|
||||
#include <string_view>
|
||||
namespace sqlite
|
||||
{
|
||||
typedef const std::string_view str_ref;
|
||||
typedef const std::u16string_view u16str_ref;
|
||||
}
|
||||
#else
|
||||
namespace sqlite
|
||||
{
|
||||
typedef const std::string& str_ref;
|
||||
typedef const std::u16string& u16str_ref;
|
||||
}
|
||||
#endif
|
||||
#include "../../sqlite3.h"
|
||||
#include "errors.h"
|
||||
|
||||
namespace sqlite {
|
||||
template<class T, int Type, class = void>
|
||||
struct has_sqlite_type : std::false_type {};
|
||||
|
||||
template<class T>
|
||||
using is_sqlite_value = std::integral_constant<bool, false
|
||||
|| has_sqlite_type<T, SQLITE_NULL>::value
|
||||
|| has_sqlite_type<T, SQLITE_INTEGER>::value
|
||||
|| has_sqlite_type<T, SQLITE_FLOAT>::value
|
||||
|| has_sqlite_type<T, SQLITE_TEXT>::value
|
||||
|| has_sqlite_type<T, SQLITE_BLOB>::value
|
||||
>;
|
||||
|
||||
template<class T, int Type>
|
||||
struct has_sqlite_type<T&, Type> : has_sqlite_type<T, Type> {};
|
||||
template<class T, int Type>
|
||||
struct has_sqlite_type<const T, Type> : has_sqlite_type<T, Type> {};
|
||||
template<class T, int Type>
|
||||
struct has_sqlite_type<volatile T, Type> : has_sqlite_type<T, Type> {};
|
||||
|
||||
template<class T>
|
||||
struct result_type {
|
||||
using type = T;
|
||||
constexpr result_type() = default;
|
||||
template<class U, class = typename std::enable_if<std::is_assignable<U, T>::value>>
|
||||
constexpr result_type(result_type<U>) { }
|
||||
};
|
||||
|
||||
// int
|
||||
template<>
|
||||
struct has_sqlite_type<int, SQLITE_INTEGER> : std::true_type {};
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const int& val) {
|
||||
return sqlite3_bind_int(stmt, inx, val);
|
||||
}
|
||||
inline void store_result_in_db(sqlite3_context* db, const int& val) {
|
||||
sqlite3_result_int(db, val);
|
||||
}
|
||||
inline int get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<int>) {
|
||||
return sqlite3_column_type(stmt, inx) == SQLITE_NULL ? 0 :
|
||||
sqlite3_column_int(stmt, inx);
|
||||
}
|
||||
inline int get_val_from_db(sqlite3_value *value, result_type<int>) {
|
||||
return sqlite3_value_type(value) == SQLITE_NULL ? 0 :
|
||||
sqlite3_value_int(value);
|
||||
}
|
||||
|
||||
// sqlite_int64
|
||||
template<>
|
||||
struct has_sqlite_type<sqlite_int64, SQLITE_INTEGER, void> : std::true_type {};
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const sqlite_int64& val) {
|
||||
return sqlite3_bind_int64(stmt, inx, val);
|
||||
}
|
||||
inline void store_result_in_db(sqlite3_context* db, const sqlite_int64& val) {
|
||||
sqlite3_result_int64(db, val);
|
||||
}
|
||||
inline sqlite_int64 get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<sqlite_int64 >) {
|
||||
return sqlite3_column_type(stmt, inx) == SQLITE_NULL ? 0 :
|
||||
sqlite3_column_int64(stmt, inx);
|
||||
}
|
||||
inline sqlite3_int64 get_val_from_db(sqlite3_value *value, result_type<sqlite3_int64>) {
|
||||
return sqlite3_value_type(value) == SQLITE_NULL ? 0 :
|
||||
sqlite3_value_int64(value);
|
||||
}
|
||||
|
||||
// float
|
||||
template<>
|
||||
struct has_sqlite_type<float, SQLITE_FLOAT, void> : std::true_type {};
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const float& val) {
|
||||
return sqlite3_bind_double(stmt, inx, double(val));
|
||||
}
|
||||
inline void store_result_in_db(sqlite3_context* db, const float& val) {
|
||||
sqlite3_result_double(db, val);
|
||||
}
|
||||
inline float get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<float>) {
|
||||
return sqlite3_column_type(stmt, inx) == SQLITE_NULL ? 0 :
|
||||
sqlite3_column_double(stmt, inx);
|
||||
}
|
||||
inline float get_val_from_db(sqlite3_value *value, result_type<float>) {
|
||||
return sqlite3_value_type(value) == SQLITE_NULL ? 0 :
|
||||
sqlite3_value_double(value);
|
||||
}
|
||||
|
||||
// double
|
||||
template<>
|
||||
struct has_sqlite_type<double, SQLITE_FLOAT, void> : std::true_type {};
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const double& val) {
|
||||
return sqlite3_bind_double(stmt, inx, val);
|
||||
}
|
||||
inline void store_result_in_db(sqlite3_context* db, const double& val) {
|
||||
sqlite3_result_double(db, val);
|
||||
}
|
||||
inline double get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<double>) {
|
||||
return sqlite3_column_type(stmt, inx) == SQLITE_NULL ? 0 :
|
||||
sqlite3_column_double(stmt, inx);
|
||||
}
|
||||
inline double get_val_from_db(sqlite3_value *value, result_type<double>) {
|
||||
return sqlite3_value_type(value) == SQLITE_NULL ? 0 :
|
||||
sqlite3_value_double(value);
|
||||
}
|
||||
|
||||
/* for nullptr support */
|
||||
template<>
|
||||
struct has_sqlite_type<std::nullptr_t, SQLITE_NULL, void> : std::true_type {};
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, std::nullptr_t) {
|
||||
return sqlite3_bind_null(stmt, inx);
|
||||
}
|
||||
inline void store_result_in_db(sqlite3_context* db, std::nullptr_t) {
|
||||
sqlite3_result_null(db);
|
||||
}
|
||||
|
||||
#ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT
|
||||
template<>
|
||||
struct has_sqlite_type<std::monostate, SQLITE_NULL, void> : std::true_type {};
|
||||
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, std::monostate) {
|
||||
return sqlite3_bind_null(stmt, inx);
|
||||
}
|
||||
inline void store_result_in_db(sqlite3_context* db, std::monostate) {
|
||||
sqlite3_result_null(db);
|
||||
}
|
||||
inline std::monostate get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::monostate>) {
|
||||
return std::monostate();
|
||||
}
|
||||
inline std::monostate get_val_from_db(sqlite3_value *value, result_type<std::monostate>) {
|
||||
return std::monostate();
|
||||
}
|
||||
#endif
|
||||
|
||||
// str_ref
|
||||
template<>
|
||||
struct has_sqlite_type<std::string, SQLITE_BLOB, void> : std::true_type {}; //
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, str_ref val) {
|
||||
return sqlite3_bind_blob(stmt, inx, val.data(), val.length(), SQLITE_TRANSIENT);
|
||||
}
|
||||
|
||||
// Convert char* to string_view to trigger op<<(..., const str_ref )
|
||||
template<std::size_t N> inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const char(&STR)[N]) {
|
||||
return sqlite3_bind_blob(stmt, inx, &STR[0], N-1, SQLITE_TRANSIENT);
|
||||
}
|
||||
|
||||
inline std::string get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::string>) {
|
||||
auto type = sqlite3_column_type(stmt, inx);
|
||||
switch (type) {
|
||||
case SQLITE_INTEGER:
|
||||
return std::to_string(sqlite3_column_int64(stmt, inx));
|
||||
case SQLITE_FLOAT:
|
||||
return std::to_string(sqlite3_column_double(stmt, inx));
|
||||
case SQLITE_BLOB: // It's important to support both text and blob data as txdb has some text and trie has some blob
|
||||
return std::string(reinterpret_cast<char const *>(sqlite3_column_blob(stmt, inx)), sqlite3_column_bytes(stmt, inx));
|
||||
case SQLITE3_TEXT:
|
||||
return std::string(reinterpret_cast<char const *>(sqlite3_column_text(stmt, inx)), sqlite3_column_bytes(stmt, inx));
|
||||
}
|
||||
return std::string(); // NULL
|
||||
}
|
||||
inline std::string get_val_from_db(sqlite3_value *value, result_type<std::string >) {
|
||||
auto type = sqlite3_value_type(value);
|
||||
switch (type) {
|
||||
case SQLITE_INTEGER:
|
||||
return std::to_string(sqlite3_value_int64(value));
|
||||
case SQLITE_FLOAT:
|
||||
return std::to_string(sqlite3_value_double(value));
|
||||
case SQLITE_BLOB:
|
||||
return std::string(reinterpret_cast<char const *>(sqlite3_value_blob(value)), sqlite3_value_bytes(value));
|
||||
case SQLITE3_TEXT:
|
||||
return std::string(reinterpret_cast<char const *>(sqlite3_value_text(value)), sqlite3_value_bytes(value));
|
||||
}
|
||||
return std::string(); // NULL
|
||||
}
|
||||
|
||||
inline void store_result_in_db(sqlite3_context* db, str_ref val) {
|
||||
sqlite3_result_blob(db, val.data(), val.length(), SQLITE_TRANSIENT);
|
||||
}
|
||||
// u16str_ref
|
||||
template<>
|
||||
struct has_sqlite_type<std::u16string, SQLITE3_TEXT, void> : std::true_type {};
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, u16str_ref val) {
|
||||
return sqlite3_bind_text16(stmt, inx, val.data(), sizeof(char16_t) * val.length(), SQLITE_TRANSIENT);
|
||||
}
|
||||
|
||||
// Convert char* to string_view to trigger op<<(..., const str_ref )
|
||||
template<std::size_t N> inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const char16_t(&STR)[N]) {
|
||||
return sqlite3_bind_text16(stmt, inx, &STR[0], sizeof(char16_t) * (N-1), SQLITE_TRANSIENT);
|
||||
}
|
||||
|
||||
inline std::u16string get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::u16string>) {
|
||||
return sqlite3_column_type(stmt, inx) == SQLITE_NULL ? std::u16string() :
|
||||
std::u16string(reinterpret_cast<char16_t const *>(sqlite3_column_text16(stmt, inx)), sqlite3_column_bytes16(stmt, inx));
|
||||
}
|
||||
inline std::u16string get_val_from_db(sqlite3_value *value, result_type<std::u16string>) {
|
||||
return sqlite3_value_type(value) == SQLITE_NULL ? std::u16string() :
|
||||
std::u16string(reinterpret_cast<char16_t const *>(sqlite3_value_text16(value)), sqlite3_value_bytes16(value));
|
||||
}
|
||||
|
||||
inline void store_result_in_db(sqlite3_context* db, u16str_ref val) {
|
||||
sqlite3_result_text16(db, val.data(), sizeof(char16_t) * val.length(), SQLITE_TRANSIENT);
|
||||
}
|
||||
|
||||
// Other integer types
|
||||
template<class Integral>
|
||||
struct has_sqlite_type<Integral, SQLITE_INTEGER, typename std::enable_if<std::is_integral<Integral>::value>::type> : std::true_type {};
|
||||
|
||||
template<class Integral, class = typename std::enable_if<std::is_integral<Integral>::value>::type>
|
||||
inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const Integral& val) {
|
||||
return bind_col_in_db(stmt, inx, static_cast<sqlite3_int64>(val));
|
||||
}
|
||||
template<class Integral, class = std::enable_if<std::is_integral<Integral>::type>>
|
||||
inline void store_result_in_db(sqlite3_context* db, const Integral& val) {
|
||||
store_result_in_db(db, static_cast<sqlite3_int64>(val));
|
||||
}
|
||||
template<class Integral, class = typename std::enable_if<std::is_integral<Integral>::value>::type>
|
||||
inline Integral get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<Integral>) {
|
||||
return get_col_from_db(stmt, inx, result_type<sqlite3_int64>());
|
||||
}
|
||||
template<class Integral, class = typename std::enable_if<std::is_integral<Integral>::value>::type>
|
||||
inline Integral get_val_from_db(sqlite3_value *value, result_type<Integral>) {
|
||||
return get_val_from_db(value, result_type<sqlite3_int64>());
|
||||
}
|
||||
|
||||
// vector<T, A>
|
||||
template<typename T, typename A>
|
||||
struct has_sqlite_type<std::vector<T, A>, SQLITE_BLOB, void> : std::true_type {};
|
||||
|
||||
template<typename T, typename A> inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const std::vector<T, A>& vec) {
|
||||
void const* buf = reinterpret_cast<void const *>(vec.data());
|
||||
int bytes = vec.size() * sizeof(T);
|
||||
return sqlite3_bind_blob(stmt, inx, buf, bytes, SQLITE_TRANSIENT);
|
||||
}
|
||||
template<typename T, typename A> inline void store_result_in_db(sqlite3_context* db, const std::vector<T, A>& vec) {
|
||||
void const* buf = reinterpret_cast<void const *>(vec.data());
|
||||
int bytes = vec.size() * sizeof(T);
|
||||
sqlite3_result_blob(db, buf, bytes, SQLITE_TRANSIENT);
|
||||
}
|
||||
template<typename T, typename A> inline std::vector<T, A> get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::vector<T, A>>) {
|
||||
if(sqlite3_column_type(stmt, inx) == SQLITE_NULL) {
|
||||
return {};
|
||||
}
|
||||
int bytes = sqlite3_column_bytes(stmt, inx);
|
||||
T const* buf = reinterpret_cast<T const *>(sqlite3_column_blob(stmt, inx));
|
||||
return std::vector<T, A>(buf, buf + bytes/sizeof(T));
|
||||
}
|
||||
template<typename T, typename A> inline std::vector<T, A> get_val_from_db(sqlite3_value *value, result_type<std::vector<T, A>>) {
|
||||
if(sqlite3_value_type(value) == SQLITE_NULL) {
|
||||
return {};
|
||||
}
|
||||
int bytes = sqlite3_value_bytes(value);
|
||||
T const* buf = reinterpret_cast<T const *>(sqlite3_value_blob(value));
|
||||
return std::vector<T, A>(buf, buf + bytes/sizeof(T));
|
||||
}
|
||||
|
||||
/* for unique_ptr<T> support */
|
||||
template<typename T, int Type>
|
||||
struct has_sqlite_type<std::unique_ptr<T>, Type, void> : has_sqlite_type<T, Type> {};
|
||||
template<typename T>
|
||||
struct has_sqlite_type<std::unique_ptr<T>, SQLITE_NULL, void> : std::true_type {};
|
||||
|
||||
template<typename T> inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const std::unique_ptr<T>& val) {
|
||||
return val ? bind_col_in_db(stmt, inx, *val) : bind_col_in_db(stmt, inx, nullptr);
|
||||
}
|
||||
template<typename T> inline std::unique_ptr<T> get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::unique_ptr<T>>) {
|
||||
if(sqlite3_column_type(stmt, inx) == SQLITE_NULL) {
|
||||
return nullptr;
|
||||
}
|
||||
return std::make_unique<T>(get_col_from_db(stmt, inx, result_type<T>()));
|
||||
}
|
||||
template<typename T> inline std::unique_ptr<T> get_val_from_db(sqlite3_value *value, result_type<std::unique_ptr<T>>) {
|
||||
if(sqlite3_value_type(value) == SQLITE_NULL) {
|
||||
return nullptr;
|
||||
}
|
||||
return std::make_unique<T>(get_val_from_db(value, result_type<T>()));
|
||||
}
|
||||
|
||||
// std::optional support for NULL values
|
||||
#ifdef MODERN_SQLITE_STD_OPTIONAL_SUPPORT
|
||||
template<class T>
|
||||
using optional = std::optional<T>;
|
||||
|
||||
template<typename T, int Type>
|
||||
struct has_sqlite_type<optional<T>, Type, void> : has_sqlite_type<T, Type> {};
|
||||
template<typename T>
|
||||
struct has_sqlite_type<optional<T>, SQLITE_NULL, void> : std::true_type {};
|
||||
|
||||
template <typename OptionalT> inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const optional<OptionalT>& val) {
|
||||
return val ? bind_col_in_db(stmt, inx, *val) : bind_col_in_db(stmt, inx, nullptr);
|
||||
}
|
||||
template <typename OptionalT> inline void store_result_in_db(sqlite3_context* db, const optional<OptionalT>& val) {
|
||||
if(val)
|
||||
store_result_in_db(db, *val);
|
||||
else
|
||||
sqlite3_result_null(db);
|
||||
}
|
||||
|
||||
template <typename OptionalT> inline optional<OptionalT> get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<optional<OptionalT>>) {
|
||||
if(sqlite3_column_type(stmt, inx) == SQLITE_NULL) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::make_optional(get_col_from_db(stmt, inx, result_type<OptionalT>()));
|
||||
}
|
||||
template <typename OptionalT> inline optional<OptionalT> get_val_from_db(sqlite3_value *value, result_type<optional<OptionalT>>) {
|
||||
if(sqlite3_value_type(value) == SQLITE_NULL) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::make_optional(get_val_from_db(value, result_type<OptionalT>()));
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef MODERN_SQLITE_STD_VARIANT_SUPPORT
|
||||
namespace detail {
|
||||
template<class T, class U>
|
||||
struct tag_trait : U { using tag = T; };
|
||||
}
|
||||
|
||||
template<int Type, class ...Options>
|
||||
struct has_sqlite_type<std::variant<Options...>, Type, void> : std::disjunction<detail::tag_trait<Options, has_sqlite_type<Options, Type>>...> {};
|
||||
|
||||
namespace detail {
|
||||
template<int Type, typename ...Options, typename Callback, typename first_compatible = has_sqlite_type<std::variant<Options...>, Type>>
|
||||
inline std::variant<Options...> variant_select_type(Callback &&callback) {
|
||||
if constexpr(first_compatible::value)
|
||||
return callback(result_type<typename first_compatible::tag>());
|
||||
else
|
||||
throw errors::mismatch("The value is unsupported by this variant.", "", SQLITE_MISMATCH);
|
||||
}
|
||||
template<typename ...Options, typename Callback> inline decltype(auto) variant_select(int type, Callback &&callback) {
|
||||
switch(type) {
|
||||
case SQLITE_NULL:
|
||||
return variant_select_type<SQLITE_NULL, Options...>(std::forward<Callback>(callback));
|
||||
case SQLITE_INTEGER:
|
||||
return variant_select_type<SQLITE_INTEGER, Options...>(std::forward<Callback>(callback));
|
||||
case SQLITE_FLOAT:
|
||||
return variant_select_type<SQLITE_FLOAT, Options...>(std::forward<Callback>(callback));
|
||||
case SQLITE_TEXT:
|
||||
return variant_select_type<SQLITE_TEXT, Options...>(std::forward<Callback>(callback));
|
||||
case SQLITE_BLOB:
|
||||
return variant_select_type<SQLITE_BLOB, Options...>(std::forward<Callback>(callback));
|
||||
}
|
||||
#ifdef _MSC_VER
|
||||
__assume(false);
|
||||
#else
|
||||
__builtin_unreachable();
|
||||
#endif
|
||||
}
|
||||
}
|
||||
template <typename ...Args> inline int bind_col_in_db(sqlite3_stmt* stmt, int inx, const std::variant<Args...>& val) {
|
||||
return std::visit([&](auto &&opt) {return bind_col_in_db(stmt, inx, std::forward<decltype(opt)>(opt));}, val);
|
||||
}
|
||||
template <typename ...Args> inline void store_result_in_db(sqlite3_context* db, const std::variant<Args...>& val) {
|
||||
std::visit([&](auto &&opt) {store_result_in_db(db, std::forward<decltype(opt)>(opt));}, val);
|
||||
}
|
||||
template <typename ...Args> inline std::variant<Args...> get_col_from_db(sqlite3_stmt* stmt, int inx, result_type<std::variant<Args...>>) {
|
||||
return detail::variant_select<Args...>(sqlite3_column_type(stmt, inx), [&](auto v) {
|
||||
return std::variant<Args...>(std::in_place_type<typename decltype(v)::type>, get_col_from_db(stmt, inx, v));
|
||||
});
|
||||
}
|
||||
template <typename ...Args> inline std::variant<Args...> get_val_from_db(sqlite3_value *value, result_type<std::variant<Args...>>) {
|
||||
return detail::variant_select<Args...>(sqlite3_value_type(value), [&](auto v) {
|
||||
return std::variant<Args...>(std::in_place_type<typename decltype(v)::type>, get_val_from_db(value, v));
|
||||
});
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
|
||||
namespace sqlite {
|
||||
namespace utility {
|
||||
|
||||
template<typename> struct function_traits;
|
||||
|
||||
template <typename Function>
|
||||
struct function_traits : public function_traits<
|
||||
decltype(&std::remove_reference<Function>::type::operator())
|
||||
> { };
|
||||
|
||||
template <
|
||||
typename ClassType,
|
||||
typename ReturnType,
|
||||
typename... Arguments
|
||||
>
|
||||
struct function_traits<
|
||||
ReturnType(ClassType::*)(Arguments...) const
|
||||
> : function_traits<ReturnType(*)(Arguments...)> { };
|
||||
|
||||
/* support the non-const operator ()
|
||||
* this will work with user defined functors */
|
||||
template <
|
||||
typename ClassType,
|
||||
typename ReturnType,
|
||||
typename... Arguments
|
||||
>
|
||||
struct function_traits<
|
||||
ReturnType(ClassType::*)(Arguments...)
|
||||
> : function_traits<ReturnType(*)(Arguments...)> { };
|
||||
|
||||
template <
|
||||
typename ReturnType,
|
||||
typename... Arguments
|
||||
>
|
||||
struct function_traits<
|
||||
ReturnType(*)(Arguments...)
|
||||
> {
|
||||
typedef ReturnType result_type;
|
||||
|
||||
using argument_tuple = std::tuple<Arguments...>;
|
||||
template <std::size_t Index>
|
||||
using argument = typename std::tuple_element<
|
||||
Index,
|
||||
argument_tuple
|
||||
>::type;
|
||||
|
||||
static const std::size_t arity = sizeof...(Arguments);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
|
||||
// Consider that std::uncaught_exceptions is available if explicitly indicated
|
||||
// by the standard library, if compiler advertises full C++17 support or, as a
|
||||
// special case, for MSVS 2015+ (which doesn't define __cplusplus correctly by
|
||||
// default as of 2017.7 version and couldn't do it at all until it).
|
||||
#ifndef MODERN_SQLITE_UNCAUGHT_EXCEPTIONS_SUPPORT
|
||||
#ifdef __cpp_lib_uncaught_exceptions
|
||||
#define MODERN_SQLITE_UNCAUGHT_EXCEPTIONS_SUPPORT
|
||||
#elif __cplusplus >= 201703L
|
||||
#define MODERN_SQLITE_UNCAUGHT_EXCEPTIONS_SUPPORT
|
||||
#elif defined(_MSC_VER) && _MSC_VER >= 1900
|
||||
#define MODERN_SQLITE_UNCAUGHT_EXCEPTIONS_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace sqlite {
|
||||
namespace utility {
|
||||
#ifdef MODERN_SQLITE_UNCAUGHT_EXCEPTIONS_SUPPORT
|
||||
class UncaughtExceptionDetector {
|
||||
public:
|
||||
operator bool() {
|
||||
return count != std::uncaught_exceptions();
|
||||
}
|
||||
private:
|
||||
int count = std::uncaught_exceptions();
|
||||
};
|
||||
#else
|
||||
class UncaughtExceptionDetector {
|
||||
public:
|
||||
operator bool() {
|
||||
return std::uncaught_exception();
|
||||
}
|
||||
};
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <locale>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
|
||||
#include "../errors.h"
|
||||
|
||||
namespace sqlite {
|
||||
namespace utility {
|
||||
inline std::string utf16_to_utf8(u16str_ref input) {
|
||||
struct : std::codecvt<char16_t, char, std::mbstate_t> {
|
||||
} codecvt;
|
||||
std::mbstate_t state{};
|
||||
std::string result((std::max)(input.size() * 3 / 2, std::size_t(4)), '\0');
|
||||
const char16_t *remaining_input = input.data();
|
||||
std::size_t produced_output = 0;
|
||||
while(true) {
|
||||
char *used_output;
|
||||
switch(codecvt.out(state, remaining_input, &input[input.size()],
|
||||
remaining_input, &result[produced_output],
|
||||
&result[result.size() - 1] + 1, used_output)) {
|
||||
case std::codecvt_base::ok:
|
||||
result.resize(used_output - result.data());
|
||||
return result;
|
||||
case std::codecvt_base::noconv:
|
||||
// This should be unreachable
|
||||
case std::codecvt_base::error:
|
||||
throw errors::invalid_utf16("Invalid UTF-16 input", "");
|
||||
case std::codecvt_base::partial:
|
||||
if(used_output == result.data() + produced_output)
|
||||
throw errors::invalid_utf16("Unexpected end of input", "");
|
||||
produced_output = used_output - result.data();
|
||||
result.resize(
|
||||
result.size()
|
||||
+ (std::max)((&input[input.size()] - remaining_input) * 3 / 2,
|
||||
std::ptrdiff_t(4)));
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace utility
|
||||
} // namespace sqlite
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,638 +0,0 @@
|
||||
/*
|
||||
** 2006 June 7
|
||||
**
|
||||
** The author disclaims copyright to this source code. In place of
|
||||
** a legal notice, here is a blessing:
|
||||
**
|
||||
** May you do good and not evil.
|
||||
** May you find forgiveness for yourself and forgive others.
|
||||
** May you share freely, never taking more than you give.
|
||||
**
|
||||
*************************************************************************
|
||||
** This header file defines the SQLite interface for use by
|
||||
** shared libraries that want to be imported as extensions into
|
||||
** an SQLite instance. Shared libraries that intend to be loaded
|
||||
** as extensions by SQLite should #include this file instead of
|
||||
** sqlite3.h.
|
||||
*/
|
||||
#ifndef SQLITE3EXT_H
|
||||
#define SQLITE3EXT_H
|
||||
#include "sqlite3.h"
|
||||
|
||||
/*
|
||||
** The following structure holds pointers to all of the SQLite API
|
||||
** routines.
|
||||
**
|
||||
** WARNING: In order to maintain backwards compatibility, add new
|
||||
** interfaces to the end of this structure only. If you insert new
|
||||
** interfaces in the middle of this structure, then older different
|
||||
** versions of SQLite will not be able to load each other's shared
|
||||
** libraries!
|
||||
*/
|
||||
struct sqlite3_api_routines {
|
||||
void * (*aggregate_context)(sqlite3_context*,int nBytes);
|
||||
int (*aggregate_count)(sqlite3_context*);
|
||||
int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
|
||||
int (*bind_double)(sqlite3_stmt*,int,double);
|
||||
int (*bind_int)(sqlite3_stmt*,int,int);
|
||||
int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
|
||||
int (*bind_null)(sqlite3_stmt*,int);
|
||||
int (*bind_parameter_count)(sqlite3_stmt*);
|
||||
int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
|
||||
const char * (*bind_parameter_name)(sqlite3_stmt*,int);
|
||||
int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
|
||||
int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
|
||||
int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
|
||||
int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
|
||||
int (*busy_timeout)(sqlite3*,int ms);
|
||||
int (*changes)(sqlite3*);
|
||||
int (*close)(sqlite3*);
|
||||
int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
|
||||
int eTextRep,const char*));
|
||||
int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
|
||||
int eTextRep,const void*));
|
||||
const void * (*column_blob)(sqlite3_stmt*,int iCol);
|
||||
int (*column_bytes)(sqlite3_stmt*,int iCol);
|
||||
int (*column_bytes16)(sqlite3_stmt*,int iCol);
|
||||
int (*column_count)(sqlite3_stmt*pStmt);
|
||||
const char * (*column_database_name)(sqlite3_stmt*,int);
|
||||
const void * (*column_database_name16)(sqlite3_stmt*,int);
|
||||
const char * (*column_decltype)(sqlite3_stmt*,int i);
|
||||
const void * (*column_decltype16)(sqlite3_stmt*,int);
|
||||
double (*column_double)(sqlite3_stmt*,int iCol);
|
||||
int (*column_int)(sqlite3_stmt*,int iCol);
|
||||
sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
|
||||
const char * (*column_name)(sqlite3_stmt*,int);
|
||||
const void * (*column_name16)(sqlite3_stmt*,int);
|
||||
const char * (*column_origin_name)(sqlite3_stmt*,int);
|
||||
const void * (*column_origin_name16)(sqlite3_stmt*,int);
|
||||
const char * (*column_table_name)(sqlite3_stmt*,int);
|
||||
const void * (*column_table_name16)(sqlite3_stmt*,int);
|
||||
const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
|
||||
const void * (*column_text16)(sqlite3_stmt*,int iCol);
|
||||
int (*column_type)(sqlite3_stmt*,int iCol);
|
||||
sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
|
||||
void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
|
||||
int (*complete)(const char*sql);
|
||||
int (*complete16)(const void*sql);
|
||||
int (*create_collation)(sqlite3*,const char*,int,void*,
|
||||
int(*)(void*,int,const void*,int,const void*));
|
||||
int (*create_collation16)(sqlite3*,const void*,int,void*,
|
||||
int(*)(void*,int,const void*,int,const void*));
|
||||
int (*create_function)(sqlite3*,const char*,int,int,void*,
|
||||
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xFinal)(sqlite3_context*));
|
||||
int (*create_function16)(sqlite3*,const void*,int,int,void*,
|
||||
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xFinal)(sqlite3_context*));
|
||||
int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
|
||||
int (*data_count)(sqlite3_stmt*pStmt);
|
||||
sqlite3 * (*db_handle)(sqlite3_stmt*);
|
||||
int (*declare_vtab)(sqlite3*,const char*);
|
||||
int (*enable_shared_cache)(int);
|
||||
int (*errcode)(sqlite3*db);
|
||||
const char * (*errmsg)(sqlite3*);
|
||||
const void * (*errmsg16)(sqlite3*);
|
||||
int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
|
||||
int (*expired)(sqlite3_stmt*);
|
||||
int (*finalize)(sqlite3_stmt*pStmt);
|
||||
void (*free)(void*);
|
||||
void (*free_table)(char**result);
|
||||
int (*get_autocommit)(sqlite3*);
|
||||
void * (*get_auxdata)(sqlite3_context*,int);
|
||||
int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
|
||||
int (*global_recover)(void);
|
||||
void (*interruptx)(sqlite3*);
|
||||
sqlite_int64 (*last_insert_rowid)(sqlite3*);
|
||||
const char * (*libversion)(void);
|
||||
int (*libversion_number)(void);
|
||||
void *(*malloc)(int);
|
||||
char * (*mprintf)(const char*,...);
|
||||
int (*open)(const char*,sqlite3**);
|
||||
int (*open16)(const void*,sqlite3**);
|
||||
int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
|
||||
int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
|
||||
void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
|
||||
void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
|
||||
void *(*realloc)(void*,int);
|
||||
int (*reset)(sqlite3_stmt*pStmt);
|
||||
void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
|
||||
void (*result_double)(sqlite3_context*,double);
|
||||
void (*result_error)(sqlite3_context*,const char*,int);
|
||||
void (*result_error16)(sqlite3_context*,const void*,int);
|
||||
void (*result_int)(sqlite3_context*,int);
|
||||
void (*result_int64)(sqlite3_context*,sqlite_int64);
|
||||
void (*result_null)(sqlite3_context*);
|
||||
void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
|
||||
void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
|
||||
void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
|
||||
void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
|
||||
void (*result_value)(sqlite3_context*,sqlite3_value*);
|
||||
void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
|
||||
int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
|
||||
const char*,const char*),void*);
|
||||
void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
|
||||
char * (*xsnprintf)(int,char*,const char*,...);
|
||||
int (*step)(sqlite3_stmt*);
|
||||
int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
|
||||
char const**,char const**,int*,int*,int*);
|
||||
void (*thread_cleanup)(void);
|
||||
int (*total_changes)(sqlite3*);
|
||||
void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
|
||||
int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
|
||||
void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
|
||||
sqlite_int64),void*);
|
||||
void * (*user_data)(sqlite3_context*);
|
||||
const void * (*value_blob)(sqlite3_value*);
|
||||
int (*value_bytes)(sqlite3_value*);
|
||||
int (*value_bytes16)(sqlite3_value*);
|
||||
double (*value_double)(sqlite3_value*);
|
||||
int (*value_int)(sqlite3_value*);
|
||||
sqlite_int64 (*value_int64)(sqlite3_value*);
|
||||
int (*value_numeric_type)(sqlite3_value*);
|
||||
const unsigned char * (*value_text)(sqlite3_value*);
|
||||
const void * (*value_text16)(sqlite3_value*);
|
||||
const void * (*value_text16be)(sqlite3_value*);
|
||||
const void * (*value_text16le)(sqlite3_value*);
|
||||
int (*value_type)(sqlite3_value*);
|
||||
char *(*vmprintf)(const char*,va_list);
|
||||
/* Added ??? */
|
||||
int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
|
||||
/* Added by 3.3.13 */
|
||||
int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
|
||||
int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
|
||||
int (*clear_bindings)(sqlite3_stmt*);
|
||||
/* Added by 3.4.1 */
|
||||
int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
|
||||
void (*xDestroy)(void *));
|
||||
/* Added by 3.5.0 */
|
||||
int (*bind_zeroblob)(sqlite3_stmt*,int,int);
|
||||
int (*blob_bytes)(sqlite3_blob*);
|
||||
int (*blob_close)(sqlite3_blob*);
|
||||
int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
|
||||
int,sqlite3_blob**);
|
||||
int (*blob_read)(sqlite3_blob*,void*,int,int);
|
||||
int (*blob_write)(sqlite3_blob*,const void*,int,int);
|
||||
int (*create_collation_v2)(sqlite3*,const char*,int,void*,
|
||||
int(*)(void*,int,const void*,int,const void*),
|
||||
void(*)(void*));
|
||||
int (*file_control)(sqlite3*,const char*,int,void*);
|
||||
sqlite3_int64 (*memory_highwater)(int);
|
||||
sqlite3_int64 (*memory_used)(void);
|
||||
sqlite3_mutex *(*mutex_alloc)(int);
|
||||
void (*mutex_enter)(sqlite3_mutex*);
|
||||
void (*mutex_free)(sqlite3_mutex*);
|
||||
void (*mutex_leave)(sqlite3_mutex*);
|
||||
int (*mutex_try)(sqlite3_mutex*);
|
||||
int (*open_v2)(const char*,sqlite3**,int,const char*);
|
||||
int (*release_memory)(int);
|
||||
void (*result_error_nomem)(sqlite3_context*);
|
||||
void (*result_error_toobig)(sqlite3_context*);
|
||||
int (*sleep)(int);
|
||||
void (*soft_heap_limit)(int);
|
||||
sqlite3_vfs *(*vfs_find)(const char*);
|
||||
int (*vfs_register)(sqlite3_vfs*,int);
|
||||
int (*vfs_unregister)(sqlite3_vfs*);
|
||||
int (*xthreadsafe)(void);
|
||||
void (*result_zeroblob)(sqlite3_context*,int);
|
||||
void (*result_error_code)(sqlite3_context*,int);
|
||||
int (*test_control)(int, ...);
|
||||
void (*randomness)(int,void*);
|
||||
sqlite3 *(*context_db_handle)(sqlite3_context*);
|
||||
int (*extended_result_codes)(sqlite3*,int);
|
||||
int (*limit)(sqlite3*,int,int);
|
||||
sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
|
||||
const char *(*sql)(sqlite3_stmt*);
|
||||
int (*status)(int,int*,int*,int);
|
||||
int (*backup_finish)(sqlite3_backup*);
|
||||
sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
|
||||
int (*backup_pagecount)(sqlite3_backup*);
|
||||
int (*backup_remaining)(sqlite3_backup*);
|
||||
int (*backup_step)(sqlite3_backup*,int);
|
||||
const char *(*compileoption_get)(int);
|
||||
int (*compileoption_used)(const char*);
|
||||
int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
|
||||
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xFinal)(sqlite3_context*),
|
||||
void(*xDestroy)(void*));
|
||||
int (*db_config)(sqlite3*,int,...);
|
||||
sqlite3_mutex *(*db_mutex)(sqlite3*);
|
||||
int (*db_status)(sqlite3*,int,int*,int*,int);
|
||||
int (*extended_errcode)(sqlite3*);
|
||||
void (*log)(int,const char*,...);
|
||||
sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
|
||||
const char *(*sourceid)(void);
|
||||
int (*stmt_status)(sqlite3_stmt*,int,int);
|
||||
int (*strnicmp)(const char*,const char*,int);
|
||||
int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
|
||||
int (*wal_autocheckpoint)(sqlite3*,int);
|
||||
int (*wal_checkpoint)(sqlite3*,const char*);
|
||||
void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
|
||||
int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
|
||||
int (*vtab_config)(sqlite3*,int op,...);
|
||||
int (*vtab_on_conflict)(sqlite3*);
|
||||
/* Version 3.7.16 and later */
|
||||
int (*close_v2)(sqlite3*);
|
||||
const char *(*db_filename)(sqlite3*,const char*);
|
||||
int (*db_readonly)(sqlite3*,const char*);
|
||||
int (*db_release_memory)(sqlite3*);
|
||||
const char *(*errstr)(int);
|
||||
int (*stmt_busy)(sqlite3_stmt*);
|
||||
int (*stmt_readonly)(sqlite3_stmt*);
|
||||
int (*stricmp)(const char*,const char*);
|
||||
int (*uri_boolean)(const char*,const char*,int);
|
||||
sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
|
||||
const char *(*uri_parameter)(const char*,const char*);
|
||||
char *(*xvsnprintf)(int,char*,const char*,va_list);
|
||||
int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
|
||||
/* Version 3.8.7 and later */
|
||||
int (*auto_extension)(void(*)(void));
|
||||
int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
|
||||
void(*)(void*));
|
||||
int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
|
||||
void(*)(void*),unsigned char);
|
||||
int (*cancel_auto_extension)(void(*)(void));
|
||||
int (*load_extension)(sqlite3*,const char*,const char*,char**);
|
||||
void *(*malloc64)(sqlite3_uint64);
|
||||
sqlite3_uint64 (*msize)(void*);
|
||||
void *(*realloc64)(void*,sqlite3_uint64);
|
||||
void (*reset_auto_extension)(void);
|
||||
void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
|
||||
void(*)(void*));
|
||||
void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
|
||||
void(*)(void*), unsigned char);
|
||||
int (*strglob)(const char*,const char*);
|
||||
/* Version 3.8.11 and later */
|
||||
sqlite3_value *(*value_dup)(const sqlite3_value*);
|
||||
void (*value_free)(sqlite3_value*);
|
||||
int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
|
||||
int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
|
||||
/* Version 3.9.0 and later */
|
||||
unsigned int (*value_subtype)(sqlite3_value*);
|
||||
void (*result_subtype)(sqlite3_context*,unsigned int);
|
||||
/* Version 3.10.0 and later */
|
||||
int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
|
||||
int (*strlike)(const char*,const char*,unsigned int);
|
||||
int (*db_cacheflush)(sqlite3*);
|
||||
/* Version 3.12.0 and later */
|
||||
int (*system_errno)(sqlite3*);
|
||||
/* Version 3.14.0 and later */
|
||||
int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
|
||||
char *(*expanded_sql)(sqlite3_stmt*);
|
||||
/* Version 3.18.0 and later */
|
||||
void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
|
||||
/* Version 3.20.0 and later */
|
||||
int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
|
||||
sqlite3_stmt**,const char**);
|
||||
int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
|
||||
sqlite3_stmt**,const void**);
|
||||
int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
|
||||
void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
|
||||
void *(*value_pointer)(sqlite3_value*,const char*);
|
||||
int (*vtab_nochange)(sqlite3_context*);
|
||||
int (*value_nochange)(sqlite3_value*);
|
||||
const char *(*vtab_collation)(sqlite3_index_info*,int);
|
||||
/* Version 3.24.0 and later */
|
||||
int (*keyword_count)(void);
|
||||
int (*keyword_name)(int,const char**,int*);
|
||||
int (*keyword_check)(const char*,int);
|
||||
sqlite3_str *(*str_new)(sqlite3*);
|
||||
char *(*str_finish)(sqlite3_str*);
|
||||
void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
|
||||
void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
|
||||
void (*str_append)(sqlite3_str*, const char *zIn, int N);
|
||||
void (*str_appendall)(sqlite3_str*, const char *zIn);
|
||||
void (*str_appendchar)(sqlite3_str*, int N, char C);
|
||||
void (*str_reset)(sqlite3_str*);
|
||||
int (*str_errcode)(sqlite3_str*);
|
||||
int (*str_length)(sqlite3_str*);
|
||||
char *(*str_value)(sqlite3_str*);
|
||||
/* Version 3.25.0 and later */
|
||||
int (*create_window_function)(sqlite3*,const char*,int,int,void*,
|
||||
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
|
||||
void (*xFinal)(sqlite3_context*),
|
||||
void (*xValue)(sqlite3_context*),
|
||||
void (*xInv)(sqlite3_context*,int,sqlite3_value**),
|
||||
void(*xDestroy)(void*));
|
||||
/* Version 3.26.0 and later */
|
||||
const char *(*normalized_sql)(sqlite3_stmt*);
|
||||
/* Version 3.28.0 and later */
|
||||
int (*stmt_isexplain)(sqlite3_stmt*);
|
||||
int (*value_frombind)(sqlite3_value*);
|
||||
/* Version 3.30.0 and later */
|
||||
int (*drop_modules)(sqlite3*,const char**);
|
||||
};
|
||||
|
||||
/*
|
||||
** This is the function signature used for all extension entry points. It
|
||||
** is also defined in the file "loadext.c".
|
||||
*/
|
||||
typedef int (*sqlite3_loadext_entry)(
|
||||
sqlite3 *db, /* Handle to the database. */
|
||||
char **pzErrMsg, /* Used to set error string on failure. */
|
||||
const sqlite3_api_routines *pThunk /* Extension API function pointers. */
|
||||
);
|
||||
|
||||
/*
|
||||
** The following macros redefine the API routines so that they are
|
||||
** redirected through the global sqlite3_api structure.
|
||||
**
|
||||
** This header file is also used by the loadext.c source file
|
||||
** (part of the main SQLite library - not an extension) so that
|
||||
** it can get access to the sqlite3_api_routines structure
|
||||
** definition. But the main library does not want to redefine
|
||||
** the API. So the redefinition macros are only valid if the
|
||||
** SQLITE_CORE macros is undefined.
|
||||
*/
|
||||
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
|
||||
#define sqlite3_aggregate_context sqlite3_api->aggregate_context
|
||||
#ifndef SQLITE_OMIT_DEPRECATED
|
||||
#define sqlite3_aggregate_count sqlite3_api->aggregate_count
|
||||
#endif
|
||||
#define sqlite3_bind_blob sqlite3_api->bind_blob
|
||||
#define sqlite3_bind_double sqlite3_api->bind_double
|
||||
#define sqlite3_bind_int sqlite3_api->bind_int
|
||||
#define sqlite3_bind_int64 sqlite3_api->bind_int64
|
||||
#define sqlite3_bind_null sqlite3_api->bind_null
|
||||
#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
|
||||
#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
|
||||
#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
|
||||
#define sqlite3_bind_text sqlite3_api->bind_text
|
||||
#define sqlite3_bind_text16 sqlite3_api->bind_text16
|
||||
#define sqlite3_bind_value sqlite3_api->bind_value
|
||||
#define sqlite3_busy_handler sqlite3_api->busy_handler
|
||||
#define sqlite3_busy_timeout sqlite3_api->busy_timeout
|
||||
#define sqlite3_changes sqlite3_api->changes
|
||||
#define sqlite3_close sqlite3_api->close
|
||||
#define sqlite3_collation_needed sqlite3_api->collation_needed
|
||||
#define sqlite3_collation_needed16 sqlite3_api->collation_needed16
|
||||
#define sqlite3_column_blob sqlite3_api->column_blob
|
||||
#define sqlite3_column_bytes sqlite3_api->column_bytes
|
||||
#define sqlite3_column_bytes16 sqlite3_api->column_bytes16
|
||||
#define sqlite3_column_count sqlite3_api->column_count
|
||||
#define sqlite3_column_database_name sqlite3_api->column_database_name
|
||||
#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
|
||||
#define sqlite3_column_decltype sqlite3_api->column_decltype
|
||||
#define sqlite3_column_decltype16 sqlite3_api->column_decltype16
|
||||
#define sqlite3_column_double sqlite3_api->column_double
|
||||
#define sqlite3_column_int sqlite3_api->column_int
|
||||
#define sqlite3_column_int64 sqlite3_api->column_int64
|
||||
#define sqlite3_column_name sqlite3_api->column_name
|
||||
#define sqlite3_column_name16 sqlite3_api->column_name16
|
||||
#define sqlite3_column_origin_name sqlite3_api->column_origin_name
|
||||
#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
|
||||
#define sqlite3_column_table_name sqlite3_api->column_table_name
|
||||
#define sqlite3_column_table_name16 sqlite3_api->column_table_name16
|
||||
#define sqlite3_column_text sqlite3_api->column_text
|
||||
#define sqlite3_column_text16 sqlite3_api->column_text16
|
||||
#define sqlite3_column_type sqlite3_api->column_type
|
||||
#define sqlite3_column_value sqlite3_api->column_value
|
||||
#define sqlite3_commit_hook sqlite3_api->commit_hook
|
||||
#define sqlite3_complete sqlite3_api->complete
|
||||
#define sqlite3_complete16 sqlite3_api->complete16
|
||||
#define sqlite3_create_collation sqlite3_api->create_collation
|
||||
#define sqlite3_create_collation16 sqlite3_api->create_collation16
|
||||
#define sqlite3_create_function sqlite3_api->create_function
|
||||
#define sqlite3_create_function16 sqlite3_api->create_function16
|
||||
#define sqlite3_create_module sqlite3_api->create_module
|
||||
#define sqlite3_create_module_v2 sqlite3_api->create_module_v2
|
||||
#define sqlite3_data_count sqlite3_api->data_count
|
||||
#define sqlite3_db_handle sqlite3_api->db_handle
|
||||
#define sqlite3_declare_vtab sqlite3_api->declare_vtab
|
||||
#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
|
||||
#define sqlite3_errcode sqlite3_api->errcode
|
||||
#define sqlite3_errmsg sqlite3_api->errmsg
|
||||
#define sqlite3_errmsg16 sqlite3_api->errmsg16
|
||||
#define sqlite3_exec sqlite3_api->exec
|
||||
#ifndef SQLITE_OMIT_DEPRECATED
|
||||
#define sqlite3_expired sqlite3_api->expired
|
||||
#endif
|
||||
#define sqlite3_finalize sqlite3_api->finalize
|
||||
#define sqlite3_free sqlite3_api->free
|
||||
#define sqlite3_free_table sqlite3_api->free_table
|
||||
#define sqlite3_get_autocommit sqlite3_api->get_autocommit
|
||||
#define sqlite3_get_auxdata sqlite3_api->get_auxdata
|
||||
#define sqlite3_get_table sqlite3_api->get_table
|
||||
#ifndef SQLITE_OMIT_DEPRECATED
|
||||
#define sqlite3_global_recover sqlite3_api->global_recover
|
||||
#endif
|
||||
#define sqlite3_interrupt sqlite3_api->interruptx
|
||||
#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
|
||||
#define sqlite3_libversion sqlite3_api->libversion
|
||||
#define sqlite3_libversion_number sqlite3_api->libversion_number
|
||||
#define sqlite3_malloc sqlite3_api->malloc
|
||||
#define sqlite3_mprintf sqlite3_api->mprintf
|
||||
#define sqlite3_open sqlite3_api->open
|
||||
#define sqlite3_open16 sqlite3_api->open16
|
||||
#define sqlite3_prepare sqlite3_api->prepare
|
||||
#define sqlite3_prepare16 sqlite3_api->prepare16
|
||||
#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
|
||||
#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
|
||||
#define sqlite3_profile sqlite3_api->profile
|
||||
#define sqlite3_progress_handler sqlite3_api->progress_handler
|
||||
#define sqlite3_realloc sqlite3_api->realloc
|
||||
#define sqlite3_reset sqlite3_api->reset
|
||||
#define sqlite3_result_blob sqlite3_api->result_blob
|
||||
#define sqlite3_result_double sqlite3_api->result_double
|
||||
#define sqlite3_result_error sqlite3_api->result_error
|
||||
#define sqlite3_result_error16 sqlite3_api->result_error16
|
||||
#define sqlite3_result_int sqlite3_api->result_int
|
||||
#define sqlite3_result_int64 sqlite3_api->result_int64
|
||||
#define sqlite3_result_null sqlite3_api->result_null
|
||||
#define sqlite3_result_text sqlite3_api->result_text
|
||||
#define sqlite3_result_text16 sqlite3_api->result_text16
|
||||
#define sqlite3_result_text16be sqlite3_api->result_text16be
|
||||
#define sqlite3_result_text16le sqlite3_api->result_text16le
|
||||
#define sqlite3_result_value sqlite3_api->result_value
|
||||
#define sqlite3_rollback_hook sqlite3_api->rollback_hook
|
||||
#define sqlite3_set_authorizer sqlite3_api->set_authorizer
|
||||
#define sqlite3_set_auxdata sqlite3_api->set_auxdata
|
||||
#define sqlite3_snprintf sqlite3_api->xsnprintf
|
||||
#define sqlite3_step sqlite3_api->step
|
||||
#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
|
||||
#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
|
||||
#define sqlite3_total_changes sqlite3_api->total_changes
|
||||
#define sqlite3_trace sqlite3_api->trace
|
||||
#ifndef SQLITE_OMIT_DEPRECATED
|
||||
#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
|
||||
#endif
|
||||
#define sqlite3_update_hook sqlite3_api->update_hook
|
||||
#define sqlite3_user_data sqlite3_api->user_data
|
||||
#define sqlite3_value_blob sqlite3_api->value_blob
|
||||
#define sqlite3_value_bytes sqlite3_api->value_bytes
|
||||
#define sqlite3_value_bytes16 sqlite3_api->value_bytes16
|
||||
#define sqlite3_value_double sqlite3_api->value_double
|
||||
#define sqlite3_value_int sqlite3_api->value_int
|
||||
#define sqlite3_value_int64 sqlite3_api->value_int64
|
||||
#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
|
||||
#define sqlite3_value_text sqlite3_api->value_text
|
||||
#define sqlite3_value_text16 sqlite3_api->value_text16
|
||||
#define sqlite3_value_text16be sqlite3_api->value_text16be
|
||||
#define sqlite3_value_text16le sqlite3_api->value_text16le
|
||||
#define sqlite3_value_type sqlite3_api->value_type
|
||||
#define sqlite3_vmprintf sqlite3_api->vmprintf
|
||||
#define sqlite3_vsnprintf sqlite3_api->xvsnprintf
|
||||
#define sqlite3_overload_function sqlite3_api->overload_function
|
||||
#define sqlite3_prepare_v2 sqlite3_api->prepare_v2
|
||||
#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
|
||||
#define sqlite3_clear_bindings sqlite3_api->clear_bindings
|
||||
#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
|
||||
#define sqlite3_blob_bytes sqlite3_api->blob_bytes
|
||||
#define sqlite3_blob_close sqlite3_api->blob_close
|
||||
#define sqlite3_blob_open sqlite3_api->blob_open
|
||||
#define sqlite3_blob_read sqlite3_api->blob_read
|
||||
#define sqlite3_blob_write sqlite3_api->blob_write
|
||||
#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
|
||||
#define sqlite3_file_control sqlite3_api->file_control
|
||||
#define sqlite3_memory_highwater sqlite3_api->memory_highwater
|
||||
#define sqlite3_memory_used sqlite3_api->memory_used
|
||||
#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
|
||||
#define sqlite3_mutex_enter sqlite3_api->mutex_enter
|
||||
#define sqlite3_mutex_free sqlite3_api->mutex_free
|
||||
#define sqlite3_mutex_leave sqlite3_api->mutex_leave
|
||||
#define sqlite3_mutex_try sqlite3_api->mutex_try
|
||||
#define sqlite3_open_v2 sqlite3_api->open_v2
|
||||
#define sqlite3_release_memory sqlite3_api->release_memory
|
||||
#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
|
||||
#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
|
||||
#define sqlite3_sleep sqlite3_api->sleep
|
||||
#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
|
||||
#define sqlite3_vfs_find sqlite3_api->vfs_find
|
||||
#define sqlite3_vfs_register sqlite3_api->vfs_register
|
||||
#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
|
||||
#define sqlite3_threadsafe sqlite3_api->xthreadsafe
|
||||
#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
|
||||
#define sqlite3_result_error_code sqlite3_api->result_error_code
|
||||
#define sqlite3_test_control sqlite3_api->test_control
|
||||
#define sqlite3_randomness sqlite3_api->randomness
|
||||
#define sqlite3_context_db_handle sqlite3_api->context_db_handle
|
||||
#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
|
||||
#define sqlite3_limit sqlite3_api->limit
|
||||
#define sqlite3_next_stmt sqlite3_api->next_stmt
|
||||
#define sqlite3_sql sqlite3_api->sql
|
||||
#define sqlite3_status sqlite3_api->status
|
||||
#define sqlite3_backup_finish sqlite3_api->backup_finish
|
||||
#define sqlite3_backup_init sqlite3_api->backup_init
|
||||
#define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
|
||||
#define sqlite3_backup_remaining sqlite3_api->backup_remaining
|
||||
#define sqlite3_backup_step sqlite3_api->backup_step
|
||||
#define sqlite3_compileoption_get sqlite3_api->compileoption_get
|
||||
#define sqlite3_compileoption_used sqlite3_api->compileoption_used
|
||||
#define sqlite3_create_function_v2 sqlite3_api->create_function_v2
|
||||
#define sqlite3_db_config sqlite3_api->db_config
|
||||
#define sqlite3_db_mutex sqlite3_api->db_mutex
|
||||
#define sqlite3_db_status sqlite3_api->db_status
|
||||
#define sqlite3_extended_errcode sqlite3_api->extended_errcode
|
||||
#define sqlite3_log sqlite3_api->log
|
||||
#define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
|
||||
#define sqlite3_sourceid sqlite3_api->sourceid
|
||||
#define sqlite3_stmt_status sqlite3_api->stmt_status
|
||||
#define sqlite3_strnicmp sqlite3_api->strnicmp
|
||||
#define sqlite3_unlock_notify sqlite3_api->unlock_notify
|
||||
#define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
|
||||
#define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
|
||||
#define sqlite3_wal_hook sqlite3_api->wal_hook
|
||||
#define sqlite3_blob_reopen sqlite3_api->blob_reopen
|
||||
#define sqlite3_vtab_config sqlite3_api->vtab_config
|
||||
#define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
|
||||
/* Version 3.7.16 and later */
|
||||
#define sqlite3_close_v2 sqlite3_api->close_v2
|
||||
#define sqlite3_db_filename sqlite3_api->db_filename
|
||||
#define sqlite3_db_readonly sqlite3_api->db_readonly
|
||||
#define sqlite3_db_release_memory sqlite3_api->db_release_memory
|
||||
#define sqlite3_errstr sqlite3_api->errstr
|
||||
#define sqlite3_stmt_busy sqlite3_api->stmt_busy
|
||||
#define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
|
||||
#define sqlite3_stricmp sqlite3_api->stricmp
|
||||
#define sqlite3_uri_boolean sqlite3_api->uri_boolean
|
||||
#define sqlite3_uri_int64 sqlite3_api->uri_int64
|
||||
#define sqlite3_uri_parameter sqlite3_api->uri_parameter
|
||||
#define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
|
||||
#define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
|
||||
/* Version 3.8.7 and later */
|
||||
#define sqlite3_auto_extension sqlite3_api->auto_extension
|
||||
#define sqlite3_bind_blob64 sqlite3_api->bind_blob64
|
||||
#define sqlite3_bind_text64 sqlite3_api->bind_text64
|
||||
#define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
|
||||
#define sqlite3_load_extension sqlite3_api->load_extension
|
||||
#define sqlite3_malloc64 sqlite3_api->malloc64
|
||||
#define sqlite3_msize sqlite3_api->msize
|
||||
#define sqlite3_realloc64 sqlite3_api->realloc64
|
||||
#define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
|
||||
#define sqlite3_result_blob64 sqlite3_api->result_blob64
|
||||
#define sqlite3_result_text64 sqlite3_api->result_text64
|
||||
#define sqlite3_strglob sqlite3_api->strglob
|
||||
/* Version 3.8.11 and later */
|
||||
#define sqlite3_value_dup sqlite3_api->value_dup
|
||||
#define sqlite3_value_free sqlite3_api->value_free
|
||||
#define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
|
||||
#define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
|
||||
/* Version 3.9.0 and later */
|
||||
#define sqlite3_value_subtype sqlite3_api->value_subtype
|
||||
#define sqlite3_result_subtype sqlite3_api->result_subtype
|
||||
/* Version 3.10.0 and later */
|
||||
#define sqlite3_status64 sqlite3_api->status64
|
||||
#define sqlite3_strlike sqlite3_api->strlike
|
||||
#define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
|
||||
/* Version 3.12.0 and later */
|
||||
#define sqlite3_system_errno sqlite3_api->system_errno
|
||||
/* Version 3.14.0 and later */
|
||||
#define sqlite3_trace_v2 sqlite3_api->trace_v2
|
||||
#define sqlite3_expanded_sql sqlite3_api->expanded_sql
|
||||
/* Version 3.18.0 and later */
|
||||
#define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
|
||||
/* Version 3.20.0 and later */
|
||||
#define sqlite3_prepare_v3 sqlite3_api->prepare_v3
|
||||
#define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
|
||||
#define sqlite3_bind_pointer sqlite3_api->bind_pointer
|
||||
#define sqlite3_result_pointer sqlite3_api->result_pointer
|
||||
#define sqlite3_value_pointer sqlite3_api->value_pointer
|
||||
/* Version 3.22.0 and later */
|
||||
#define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
|
||||
#define sqlite3_value_nochange sqlite3_api->value_nochange
|
||||
#define sqlite3_vtab_collation sqlite3_api->vtab_collation
|
||||
/* Version 3.24.0 and later */
|
||||
#define sqlite3_keyword_count sqlite3_api->keyword_count
|
||||
#define sqlite3_keyword_name sqlite3_api->keyword_name
|
||||
#define sqlite3_keyword_check sqlite3_api->keyword_check
|
||||
#define sqlite3_str_new sqlite3_api->str_new
|
||||
#define sqlite3_str_finish sqlite3_api->str_finish
|
||||
#define sqlite3_str_appendf sqlite3_api->str_appendf
|
||||
#define sqlite3_str_vappendf sqlite3_api->str_vappendf
|
||||
#define sqlite3_str_append sqlite3_api->str_append
|
||||
#define sqlite3_str_appendall sqlite3_api->str_appendall
|
||||
#define sqlite3_str_appendchar sqlite3_api->str_appendchar
|
||||
#define sqlite3_str_reset sqlite3_api->str_reset
|
||||
#define sqlite3_str_errcode sqlite3_api->str_errcode
|
||||
#define sqlite3_str_length sqlite3_api->str_length
|
||||
#define sqlite3_str_value sqlite3_api->str_value
|
||||
/* Version 3.25.0 and later */
|
||||
#define sqlite3_create_window_function sqlite3_api->create_window_function
|
||||
/* Version 3.26.0 and later */
|
||||
#define sqlite3_normalized_sql sqlite3_api->normalized_sql
|
||||
/* Version 3.28.0 and later */
|
||||
#define sqlite3_stmt_isexplain sqlite3_api->isexplain
|
||||
#define sqlite3_value_frombind sqlite3_api->frombind
|
||||
/* Version 3.30.0 and later */
|
||||
#define sqlite3_drop_modules sqlite3_api->drop_modules
|
||||
#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
|
||||
|
||||
#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
|
||||
/* This case when the file really is being compiled as a loadable
|
||||
** extension */
|
||||
# define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
|
||||
# define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
|
||||
# define SQLITE_EXTENSION_INIT3 \
|
||||
extern const sqlite3_api_routines *sqlite3_api;
|
||||
#else
|
||||
/* This case when the file is being statically linked into the
|
||||
** application */
|
||||
# define SQLITE_EXTENSION_INIT1 /*no-op*/
|
||||
# define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
|
||||
# define SQLITE_EXTENSION_INIT3 /*no-op*/
|
||||
#endif
|
||||
|
||||
#endif /* SQLITE3EXT_H */
|
||||
@@ -1,455 +0,0 @@
|
||||
|
||||
#ifndef TAKEOVERWORKAROUNDS_H
|
||||
#define TAKEOVERWORKAROUNDS_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
|
||||
const boost::container::flat_map<std::pair<int, std::string>, int> takeoverWorkarounds = {
|
||||
{{496856, "HunterxHunterAMV"}, 496835},
|
||||
{{542978, "namethattune1"}, 542429},
|
||||
{{543508, "namethattune-5"}, 543306},
|
||||
{{546780, "forecasts"}, 546624},
|
||||
{{548730, "forecasts"}, 546780},
|
||||
{{551540, "forecasts"}, 548730},
|
||||
{{552380, "chicthinkingofyou"}, 550804},
|
||||
{{560363, "takephotowithlbryteam"}, 559962},
|
||||
{{563710, "test-img"}, 563700},
|
||||
{{566750, "itila"}, 543261},
|
||||
{{567082, "malabarismo-com-bolas-de-futebol-vs-chap"}, 563592},
|
||||
{{596860, "180mphpullsthrougheurope"}, 596757},
|
||||
{{617743, "vaccines"}, 572756},
|
||||
{{619609, "copface-slamshandcuffedteengirlintoconcrete"}, 539940},
|
||||
{{620392, "banker-exposes-satanic-elite"}, 597788},
|
||||
{{624997, "direttiva-sulle-armi-ue-in-svizzera-di"}, 567908},
|
||||
{{624997, "best-of-apex"}, 585580},
|
||||
{{629970, "cannot-ignore-my-veins"}, 629914},
|
||||
{{633058, "bio-waste-we-programmed-your-brain"}, 617185},
|
||||
{{633601, "macrolauncher-overview-first-look"}, 633058},
|
||||
{{640186, "its-up-to-you-and-i-2019"}, 639116},
|
||||
{{640241, "tor-eas-3-20"}, 592645},
|
||||
{{640522, "seadoxdark"}, 619531},
|
||||
{{640617, "lbry-przewodnik-1-instalacja"}, 451186},
|
||||
{{640623, "avxchange-2019-the-next-netflix-spotify"}, 606790},
|
||||
{{640684, "algebra-introduction"}, 624152},
|
||||
{{640684, "a-high-school-math-teacher-does-a"}, 600885},
|
||||
{{640684, "another-random-life-update"}, 600884},
|
||||
{{640684, "who-is-the-taylor-series-for"}, 600882},
|
||||
{{640684, "tedx-talk-released"}, 612303},
|
||||
{{640730, "e-mental"}, 615375},
|
||||
{{641143, "amiga-1200-bespoke-virgin-cinema"}, 623542},
|
||||
{{641161, "dreamscape-432-omega"}, 618894},
|
||||
{{641162, "2019-topstone-carbon-force-etap-axs-bike"}, 639107},
|
||||
{{641186, "arin-sings-big-floppy-penis-live-jazz-2"}, 638904},
|
||||
{{641421, "edward-snowden-on-bitcoin-and-privacy"}, 522729},
|
||||
{{641421, "what-is-libra-facebook-s-new"}, 598236},
|
||||
{{641421, "what-are-stablecoins-counter-party-risk"}, 583508},
|
||||
{{641421, "anthony-pomp-pompliano-discusses-crypto"}, 564416},
|
||||
{{641421, "tim-draper-crypto-invest-summit-2019"}, 550329},
|
||||
{{641421, "mass-adoption-and-what-will-it-take-to"}, 549781},
|
||||
{{641421, "dragonwolftech-youtube-channel-trailer"}, 567128},
|
||||
{{641421, "naomi-brockwell-s-weekly-crypto-recap"}, 540006},
|
||||
{{641421, "blockchain-based-youtube-twitter"}, 580809},
|
||||
{{641421, "andreas-antonopoulos-on-privacy-privacy"}, 533522},
|
||||
{{641817, "mexico-submits-and-big-tech-worsens"}, 582977},
|
||||
{{641817, "why-we-need-travel-bans"}, 581354},
|
||||
{{641880, "censored-by-patreon-bitchute-shares"}, 482460},
|
||||
{{641880, "crypto-wonderland"}, 485218},
|
||||
{{642168, "1-diabolo-julio-cezar-16-cbmcp-freestyle"}, 374999},
|
||||
{{642314, "tough-students"}, 615780},
|
||||
{{642697, "gamercauldronep2"}, 642153},
|
||||
{{643406, "the-most-fun-i-ve-had-in-a-long-time"}, 616506},
|
||||
{{643893, "spitshine69-and-uk-freedom-audits"}, 616876},
|
||||
{{644480, "my-mum-getting-attacked-a-duck"}, 567624},
|
||||
{{644486, "the-cryptocurrency-experiment"}, 569189},
|
||||
{{644486, "tag-you-re-it"}, 558316},
|
||||
{{644486, "orange-county-mineral-society-rock-and"}, 397138},
|
||||
{{644486, "sampling-with-the-gold-rush-nugget"}, 527960},
|
||||
{{644562, "september-15-21-a-new-way-of-doing"}, 634792},
|
||||
{{644562, "july-week-3-collective-frequency-general"}, 607942},
|
||||
{{644562, "september-8-14-growing-up-general"}, 630977},
|
||||
{{644562, "august-4-10-collective-frequency-general"}, 612307},
|
||||
{{644562, "august-11-17-collective-frequency"}, 617279},
|
||||
{{644562, "september-1-7-gentle-wake-up-call"}, 627104},
|
||||
{{644607, "no-more-lol"}, 643497},
|
||||
{{644607, "minion-masters-who-knew"}, 641313},
|
||||
{{645236, "danganronpa-3-the-end-of-hope-s-peak"}, 644153},
|
||||
{{645348, "captchabot-a-discord-bot-to-protect-your"}, 592810},
|
||||
{{645701, "the-xero-hour-saint-greta-of-thunberg"}, 644081},
|
||||
{{645701, "batman-v-superman-theological-notions"}, 590189},
|
||||
{{645918, "emacs-is-great-ep-0-init-el-from-org"}, 575666},
|
||||
{{645918, "emacs-is-great-ep-1-packages"}, 575666},
|
||||
{{645918, "emacs-is-great-ep-40-pt-2-hebrew"}, 575668},
|
||||
{{645923, "nasal-snuff-review-osp-batch-2"}, 575658},
|
||||
{{645923, "why-bit-coin"}, 575658},
|
||||
{{645929, "begin-quest"}, 598822},
|
||||
{{645929, "filthy-foe"}, 588386},
|
||||
{{645929, "unsanitary-snow"}, 588386},
|
||||
{{645929, "famispam-1-music-box"}, 588386},
|
||||
{{645929, "running-away"}, 598822},
|
||||
{{645931, "my-beloved-chris-madsen"}, 589114},
|
||||
{{645931, "space-is-consciousness-chris-madsen"}, 589116},
|
||||
{{645947, "gasifier-rocket-stove-secondary-burn"}, 590595},
|
||||
{{645949, "mouse-razer-abyssus-v2-e-mousepad"}, 591139},
|
||||
{{645949, "pr-temporada-2018-league-of-legends"}, 591138},
|
||||
{{645949, "windows-10-build-9901-pt-br"}, 591137},
|
||||
{{645949, "abrindo-pacotes-do-festival-lunar-2018"}, 591139},
|
||||
{{645949, "unboxing-camisetas-personalizadas-play-e"}, 591138},
|
||||
{{645949, "abrindo-envelopes-do-festival-lunar-2017"}, 591138},
|
||||
{{645951, "grub-my-grub-played-guruku-tersayang"}, 618033},
|
||||
{{645951, "ismeeltimepiece"}, 618038},
|
||||
{{645951, "thoughts-on-doom"}, 596485},
|
||||
{{645951, "thoughts-on-god-of-war-about-as-deep-as"}, 596485},
|
||||
{{645956, "linux-lite-3-6-see-what-s-new"}, 645195},
|
||||
{{646191, "kahlil-gibran-the-prophet-part-1"}, 597637},
|
||||
{{646551, "crypto-market-crash-should-you-sell-your"}, 442613},
|
||||
{{646551, "live-crypto-trading-and-market-analysis"}, 442615},
|
||||
{{646551, "5-reasons-trading-is-always-better-than"}, 500850},
|
||||
{{646551, "digitex-futures-dump-panic-selling-or"}, 568065},
|
||||
{{646552, "how-to-install-polarr-on-kali-linux-bynp"}, 466235},
|
||||
{{646586, "electoral-college-kids-civics-lesson"}, 430818},
|
||||
{{646602, "grapes-full-90-minute-watercolour"}, 537108},
|
||||
{{646602, "meizu-mx4-the-second-ubuntu-phone"}, 537109},
|
||||
{{646609, "how-to-set-up-the-ledger-nano-x"}, 569992},
|
||||
{{646609, "how-to-buy-ethereum"}, 482354},
|
||||
{{646609, "how-to-install-setup-the-exodus-multi"}, 482356},
|
||||
{{646609, "how-to-manage-your-passwords-using"}, 531987},
|
||||
{{646609, "cryptodad-s-live-q-a-friday-may-3rd-2019"}, 562303},
|
||||
{{646638, "resident-evil-ada-chapter-5-final"}, 605612},
|
||||
{{646639, "taurus-june-2019-career-love-tarot"}, 586910},
|
||||
{{646652, "digital-bullpen-ep-5-building-a-digital"}, 589274},
|
||||
{{646661, "sunlight"}, 591076},
|
||||
{{646661, "grasp-lab-nasa-open-mct-series"}, 589414},
|
||||
{{646663, "bunnula-s-creepers-tim-pool-s-beanie-a"}, 599669},
|
||||
{{646663, "bunnula-music-hey-ya-by-outkast"}, 605685},
|
||||
{{646663, "bunnula-tv-s-music-television-eunoia"}, 644437},
|
||||
{{646663, "the-pussy-centipede-40-sneakers-and"}, 587265},
|
||||
{{646663, "bunnula-reacts-ashton-titty-whitty"}, 596988},
|
||||
{{646677, "filip-reviews-jeromes-dream-cataracts-so"}, 589751},
|
||||
{{646691, "fascism-and-its-mobilizing-passions"}, 464342},
|
||||
{{646692, "hsb-color-layers-action-for-adobe"}, 586533},
|
||||
{{646692, "master-colorist-action-pack-extracting"}, 631830},
|
||||
{{646693, "how-to-protect-your-garden-from-animals"}, 588476},
|
||||
{{646693, "gardening-for-the-apocalypse-epic"}, 588472},
|
||||
{{646693, "my-first-bee-hive-foundationless-natural"}, 588469},
|
||||
{{646693, "dragon-fruit-and-passion-fruit-planting"}, 588470},
|
||||
{{646693, "installing-my-first-foundationless"}, 588469},
|
||||
{{646705, "first-naza-fpv"}, 590411},
|
||||
{{646717, "first-burning-man-2019-detour-034"}, 630247},
|
||||
{{646717, "why-bob-marley-was-an-idiot-test-driving"}, 477558},
|
||||
{{646717, "we-are-addicted-to-gambling-ufc-207-w"}, 481398},
|
||||
{{646717, "ghetto-swap-meet-selling-storage-lockers"}, 498291},
|
||||
{{646738, "1-kings-chapter-7-summary-and-what-god"}, 586599},
|
||||
{{646814, "brand-spanking-new-junior-high-school"}, 592378},
|
||||
{{646814, "lupe-fiasco-freestyle-at-end-of-the-weak"}, 639535},
|
||||
{{646824, "how-to-one-stroke-painting-doodles-mixed"}, 592404},
|
||||
{{646824, "acrylic-pouring-landscape-with-a-tree"}, 592404},
|
||||
{{646824, "how-to-make-a-diy-concrete-paste-planter"}, 595976},
|
||||
{{646824, "how-to-make-a-rustic-sand-planter-sand"}, 592404},
|
||||
{{646833, "3-day-festival-at-the-galilee-lake-and"}, 592842},
|
||||
{{646833, "rainbow-circle-around-the-noon-sun-above"}, 592842},
|
||||
{{646833, "energetic-self-control-demonstration"}, 623811},
|
||||
{{646833, "bees-congregating"}, 592842},
|
||||
{{646856, "formula-offroad-honefoss-sunday-track2"}, 592872},
|
||||
{{646862, "h3video1-dc-vs-mb-1"}, 593237},
|
||||
{{646862, "h3video1-iwasgoingto-load-up-gmod-but"}, 593237},
|
||||
{{646883, "watch-this-game-developer-make-a-video"}, 592593},
|
||||
{{646883, "how-to-write-secure-javascript"}, 592593},
|
||||
{{646883, "blockchain-technology-explained-2-hour"}, 592593},
|
||||
{{646888, "fl-studio-bits"}, 608155},
|
||||
{{646914, "andy-s-shed-live-s03e02-the-longest"}, 592200},
|
||||
{{646914, "gpo-telephone-776-phone-restoration"}, 592201},
|
||||
{{646916, "toxic-studios-co-stream-pubg"}, 597126},
|
||||
{{646916, "hyperlapse-of-prague-praha-from-inside"}, 597109},
|
||||
{{646933, "videobits-1"}, 597378},
|
||||
{{646933, "clouds-developing-daytime-8"}, 597378},
|
||||
{{646933, "slechtvalk-in-watertoren-bodegraven"}, 597378},
|
||||
{{646933, "timelapse-maansverduistering-16-juli"}, 605880},
|
||||
{{646933, "startrails-27"}, 597378},
|
||||
{{646933, "passing-clouds-daytime-3"}, 597378},
|
||||
{{646940, "nerdgasm-unboxing-massive-playing-cards"}, 597421},
|
||||
{{646946, "debunking-cops-volume-3-the-murder-of"}, 630570},
|
||||
{{646961, "kingsong-ks16x-electric-unicycle-250km"}, 636725},
|
||||
{{646968, "wild-mountain-goats-amazing-rock"}, 621940},
|
||||
{{646968, "no-shelter-backcountry-camping-in"}, 621940},
|
||||
{{646968, "can-i-live-in-this-through-winter-lets"}, 645750},
|
||||
{{646968, "why-i-wear-a-chest-rig-backcountry-or"}, 621940},
|
||||
{{646989, "marc-ivan-o-gorman-promo-producer-editor"}, 645656},
|
||||
{{647045, "@moraltis"}, 646367},
|
||||
{{647045, "moraltis-twitch-highlights-first-edit"}, 646368},
|
||||
{{647075, "the-3-massive-tinder-convo-mistakes"}, 629464},
|
||||
{{647075, "how-to-get-friend-zoned-via-text"}, 592298},
|
||||
{{647075, "don-t-do-this-on-tinder"}, 624591},
|
||||
{{647322, "world-of-tanks-7-kills"}, 609905},
|
||||
{{647322, "the-tier-6-auto-loading-swedish-meatball"}, 591338},
|
||||
{{647416, "hypnotic-soundscapes-garden-of-the"}, 596923},
|
||||
{{647416, "hypnotic-soundscapes-the-cauldron-sacred"}, 596928},
|
||||
{{647416, "schumann-resonance-to-theta-sweep"}, 596920},
|
||||
{{647416, "conversational-indirect-hypnosis-why"}, 596913},
|
||||
{{647493, "mimirs-brunnr"}, 590498},
|
||||
{{648143, "live-ita-completiamo-the-evil-within-2"}, 646568},
|
||||
{{648203, "why-we-love-people-that-hurt-us"}, 591128},
|
||||
{{648203, "i-didn-t-like-my-baby-and-considered"}, 591128},
|
||||
{{648220, "trade-talk-001-i-m-a-vlogger-now-fielder"}, 597303},
|
||||
{{648220, "vise-restoration-record-no-6-vise"}, 597303},
|
||||
{{648540, "amv-reign"}, 571863},
|
||||
{{648540, "amv-virus"}, 571863},
|
||||
{{648588, "audial-drift-(a-journey-into-sound)"}, 630217},
|
||||
{{648616, "quick-zbrush-tip-transpose-master-scale"}, 463205},
|
||||
{{648616, "how-to-create-3d-horns-maya-to-zbrush-2"}, 463205},
|
||||
{{648815, "arduino-based-cartridge-game-handheld"}, 593252},
|
||||
{{648815, "a-maze-update-3-new-game-modes-amazing"}, 593252},
|
||||
{{649209, "denmark-trip"}, 591428},
|
||||
{{649209, "stunning-4k-drone-footage"}, 591428},
|
||||
{{649215, "how-to-create-a-channel-and-publish-a"}, 414908},
|
||||
{{649215, "lbryclass-11-how-to-get-your-deposit"}, 632420},
|
||||
{{649543, "spring-break-madness-at-universal"}, 599698},
|
||||
{{649921, "navegador-brave-navegador-da-web-seguro"}, 649261},
|
||||
{{650191, "stream-intro"}, 591301},
|
||||
{{650946, "platelet-chan-fan-art"}, 584601},
|
||||
{{650946, "aqua-fanart"}, 584601},
|
||||
{{650946, "virginmedia-stores-password-in-plain"}, 619537},
|
||||
{{650946, "running-linux-on-android-teaser"}, 604441},
|
||||
{{650946, "hatsune-miku-ievan-polka"}, 600126},
|
||||
{{650946, "digital-security-and-privacy-2-and-a-new"}, 600135},
|
||||
{{650993, "my-editorial-comment-on-recent-youtube"}, 590305},
|
||||
{{650993, "drive-7-18-2018"}, 590305},
|
||||
{{651011, "old-world-put-on-realm-realms-gg"}, 591899},
|
||||
{{651011, "make-your-own-soundboard-with-autohotkey"}, 591899},
|
||||
{{651011, "ark-survival-https-discord-gg-ad26xa"}, 637680},
|
||||
{{651011, "minecraft-featuring-seus-8-just-came-4"}, 596488},
|
||||
{{651057, "found-footage-bikinis-at-the-beach-with"}, 593586},
|
||||
{{651057, "found-footage-sexy-mom-a-mink-stole"}, 593586},
|
||||
{{651067, "who-are-the-gentiles-gomer"}, 597094},
|
||||
{{651067, "take-back-the-kingdom-ep-2-450-million"}, 597094},
|
||||
{{651067, "mmxtac-implemented-footstep-sounds-and"}, 597094},
|
||||
{{651067, "dynasoul-s-blender-to-unreal-animated"}, 597094},
|
||||
{{651103, "calling-a-scammer-syntax-error"}, 612532},
|
||||
{{651103, "quick-highlight-of-my-day"}, 647651},
|
||||
{{651103, "calling-scammers-and-singing-christmas"}, 612531},
|
||||
{{651109, "@livingtzm"}, 637322},
|
||||
{{651109, "living-tzm-juuso-from-finland-september"}, 643412},
|
||||
{{651373, "se-voc-rir-ou-sorrir-reinicie-o-v-deo"}, 649302},
|
||||
{{651476, "what-is-pagan-online-polished-new-arpg"}, 592157},
|
||||
{{651476, "must-have-elder-scrolls-online-addons"}, 592156},
|
||||
{{651476, "who-should-play-albion-online"}, 592156},
|
||||
{{651730, "person-detection-with-keras-tensorflow"}, 621276},
|
||||
{{651730, "youtube-censorship-take-two"}, 587249},
|
||||
{{651730, "new-red-tail-shark-and-two-silver-sharks"}, 587251},
|
||||
{{651730, "around-auckland"}, 587250},
|
||||
{{651730, "humanism-in-islam"}, 587250},
|
||||
{{651730, "tigers-at-auckland-zoo"}, 587250},
|
||||
{{651730, "gravity-demonstration"}, 587250},
|
||||
{{651730, "copyright-question"}, 587249},
|
||||
{{651730, "uberg33k-the-ultimate-software-developer"}, 599522},
|
||||
{{651730, "chl-e-swarbrick-auckland-mayoral"}, 587250},
|
||||
{{651730, "code-reviews"}, 587249},
|
||||
{{651730, "raising-robots"}, 587251},
|
||||
{{651730, "teaching-python"}, 587250},
|
||||
{{651730, "kelly-tarlton-2016"}, 587250},
|
||||
{{652172, "where-is-everything"}, 589491},
|
||||
{{652172, "some-guy-and-his-camera"}, 617062},
|
||||
{{652172, "practical-information-pt-1"}, 589491},
|
||||
{{652172, "latent-vibrations"}, 589491},
|
||||
{{652172, "maldek-compilation"}, 589491},
|
||||
{{652444, "thank-you-etika-thank-you-desmond"}, 652121},
|
||||
{{652611, "plants-vs-zombies-gw2-20190827183609"}, 624339},
|
||||
{{652611, "wolfenstein-the-new-order-playthrough-6"}, 650299},
|
||||
{{652887, "a-codeigniter-cms-open-source-download"}, 652737},
|
||||
{{652966, "@pokesadventures"}, 632391},
|
||||
{{653009, "flat-earth-uk-convention-is-a-bust"}, 585786},
|
||||
{{653009, "flat-earth-reset-flat-earth-money-tree"}, 585786},
|
||||
{{653011, "veil-of-thorns-dispirit-brutal-leech-3"}, 652475},
|
||||
{{653069, "being-born-after-9-11"}, 632218},
|
||||
{{653069, "8-years-on-youtube-what-it-has-done-for"}, 637130},
|
||||
{{653069, "answering-questions-how-original"}, 521447},
|
||||
{{653069, "talking-about-my-first-comedy-stand-up"}, 583450},
|
||||
{{653069, "doing-push-ups-in-public"}, 650920},
|
||||
{{653069, "vlog-extra"}, 465997},
|
||||
{{653069, "crying-myself"}, 465997},
|
||||
{{653069, "xbox-rejection"}, 465992},
|
||||
{{653354, "msps-how-to-find-a-linux-job-where-no"}, 642537},
|
||||
{{653354, "windows-is-better-than-linux-vlog-it-and"}, 646306},
|
||||
{{653354, "luke-smith-is-wrong-about-everything"}, 507717},
|
||||
{{653354, "advice-for-those-starting-out-in-tech"}, 612452},
|
||||
{{653354, "treating-yourself-to-make-studying-more"}, 623561},
|
||||
{{653354, "lpi-linux-essential-dns-tools-vlog-what"}, 559464},
|
||||
{{653354, "is-learning-linux-worth-it-in-2019-vlog"}, 570886},
|
||||
{{653354, "huawei-linux-and-cellphones-in-2019-vlog"}, 578501},
|
||||
{{653354, "how-to-use-webmin-to-manage-linux"}, 511507},
|
||||
{{653354, "latency-concurrency-and-the-best-value"}, 596857},
|
||||
{{653354, "how-to-use-the-pomodoro-method-in-it"}, 506632},
|
||||
{{653354, "negotiating-compensation-vlog-it-and"}, 542317},
|
||||
{{653354, "procedural-goals-vs-outcome-goals-vlog"}, 626785},
|
||||
{{653354, "intro-to-raid-understanding-how-raid"}, 529341},
|
||||
{{653354, "smokeping"}, 574693},
|
||||
{{653354, "richard-stallman-should-not-be-fired"}, 634928},
|
||||
{{653354, "unusual-or-specialty-certifications-vlog"}, 620146},
|
||||
{{653354, "gratitude-and-small-projects-vlog-it"}, 564900},
|
||||
{{653354, "why-linux-on-the-smartphone-is-important"}, 649543},
|
||||
{{653354, "opportunity-costs-vlog-it-devops-career"}, 549708},
|
||||
{{653354, "double-giveaway-lpi-class-dates-and"}, 608129},
|
||||
{{653354, "linux-on-the-smartphone-in-2019-librem"}, 530426},
|
||||
{{653524, "celtic-folk-music-full-live-concert-mps"}, 589762},
|
||||
{{653745, "aftermath-of-the-mac"}, 592768},
|
||||
{{653745, "b-c-a-glock-17-threaded-barrel"}, 592770},
|
||||
{{653800, "middle-earth-shadow-of-mordor-by"}, 590229},
|
||||
{{654079, "tomand-jeremy-chirs45"}, 614296},
|
||||
{{654096, "achamos-carteira-com-grana-olha-o-que"}, 466262},
|
||||
{{654096, "viagem-bizarra-e-cansativa-ao-nordeste"}, 466263},
|
||||
{{654096, "tedio-na-tailandia-limpeza-de-area"}, 466265},
|
||||
{{654425, "schau-bung-2014-in-windischgarsten"}, 654410},
|
||||
{{654425, "mitternachtseinlage-ball-rk"}, 654410},
|
||||
{{654425, "zugabe-ball-rk-windischgarsten"}, 654412},
|
||||
{{654722, "skytrain-in-korea"}, 463145},
|
||||
{{654722, "luwak-coffee-the-shit-coffee"}, 463155},
|
||||
{{654722, "puppet-show-in-bangkok-thailand"}, 462812},
|
||||
{{654722, "kyaito-market-myanmar"}, 462813},
|
||||
{{654724, "wipeout-zombies-bo3-custom-zombies-1st"}, 589569},
|
||||
{{654724, "the-street-bo3-custom-zombies"}, 589544},
|
||||
{{654880, "wwii-airsoft-pow"}, 586968},
|
||||
{{654880, "dueling-geese-fight-to-the-death"}, 586968},
|
||||
{{654880, "wwii-airsoft-torgau-raw-footage-part4"}, 586968},
|
||||
{{655173, "april-2019-q-and-a"}, 554032},
|
||||
{{655173, "the-meaning-and-reality-of-individual"}, 607892},
|
||||
{{655173, "steven-pinker-progress-despite"}, 616984},
|
||||
{{655173, "we-make-stories-out-of-totem-poles"}, 549090},
|
||||
{{655173, "jamil-jivani-author-of-why-young-men"}, 542035},
|
||||
{{655173, "commentaries-on-jb-peterson-rebel-wisdom"}, 528898},
|
||||
{{655173, "auckland-clip-4-on-cain-and-abel"}, 629242},
|
||||
{{655173, "peterson-vs-zizek-livestream-tickets"}, 545285},
|
||||
{{655173, "auckland-clip-3-the-dawning-of-the-moral"}, 621154},
|
||||
{{655173, "religious-belief-and-the-enlightenment"}, 606269},
|
||||
{{655173, "auckland-lc-highlight-1-the-presumption"}, 565783},
|
||||
{{655173, "q-a-sir-roger-scruton-dr-jordan-b"}, 544184},
|
||||
{{655173, "cancellation-polish-national-foundation"}, 562529},
|
||||
{{655173, "the-coddling-of-the-american-mind-haidt"}, 440185},
|
||||
{{655173, "02-harris-weinstein-peterson-discussion"}, 430896},
|
||||
{{655173, "jordan-peterson-threatens-everything-of"}, 519737},
|
||||
{{655173, "on-claiming-belief-in-god-commentary"}, 581738},
|
||||
{{655173, "how-to-make-the-world-better-really-with"}, 482317},
|
||||
{{655173, "quillette-discussion-with-founder-editor"}, 413749},
|
||||
{{655173, "jb-peterson-on-free-thought-and-speech"}, 462849},
|
||||
{{655173, "marxism-zizek-peterson-official-video"}, 578453},
|
||||
{{655173, "patreon-problem-solution-dave-rubin-dr"}, 490394},
|
||||
{{655173, "next-week-st-louis-salt-lake-city"}, 445933},
|
||||
{{655173, "conversations-with-john-anderson-jordan"}, 529981},
|
||||
{{655173, "nz-australia-12-rules-tour-next-2-weeks"}, 518649},
|
||||
{{655173, "a-call-to-rebellion-for-ontario-legal"}, 285451},
|
||||
{{655173, "2016-personality-lecture-12"}, 578465},
|
||||
{{655173, "on-the-vital-necessity-of-free-speech"}, 427404},
|
||||
{{655173, "2017-01-23-social-justice-freedom-of"}, 578465},
|
||||
{{655173, "discussion-sam-harris-the-idw-and-the"}, 423332},
|
||||
{{655173, "march-2018-patreon-q-a"}, 413749},
|
||||
{{655173, "take-aim-even-badly"}, 490395},
|
||||
{{655173, "jp-f-wwbgo6a2w"}, 539940},
|
||||
{{655173, "patreon-account-deletion"}, 503477},
|
||||
{{655173, "canada-us-europe-tour-august-dec-2018"}, 413749},
|
||||
{{655173, "leaders-myth-reality-general-stanley"}, 514333},
|
||||
{{655173, "jp-ifi5kkxig3s"}, 539940},
|
||||
{{655173, "documentary-a-glitch-in-the-matrix-david"}, 413749},
|
||||
{{655173, "2017-08-14-patreon-q-and-a"}, 285451},
|
||||
{{655173, "postmodernism-history-and-diagnosis"}, 285451},
|
||||
{{655173, "23-minutes-from-maps-of-meaning-the"}, 413749},
|
||||
{{655173, "milo-forbidden-conversation"}, 578493},
|
||||
{{655173, "jp-wnjbasba-qw"}, 539940},
|
||||
{{655173, "uk-12-rules-tour-october-and-november"}, 462849},
|
||||
{{655173, "2015-maps-of-meaning-10-culture-anomaly"}, 578465},
|
||||
{{655173, "ayaan-hirsi-ali-islam-mecca-vs-medina"}, 285452},
|
||||
{{655173, "jp-f9393el2z1i"}, 539940},
|
||||
{{655173, "campus-indoctrination-the-parasitization"}, 285453},
|
||||
{{655173, "jp-owgc63khcl8"}, 539940},
|
||||
{{655173, "the-death-and-resurrection-of-christ-a"}, 413749},
|
||||
{{655173, "01-harris-weinstein-peterson-discussion"}, 430896},
|
||||
{{655173, "enlightenment-now-steven-pinker-jb"}, 413749},
|
||||
{{655173, "the-lindsay-shepherd-affair-update"}, 413749},
|
||||
{{655173, "jp-g3fwumq5k8i"}, 539940},
|
||||
{{655173, "jp-evvs3l-abv4"}, 539940},
|
||||
{{655173, "former-australian-deputy-pm-john"}, 413750},
|
||||
{{655173, "message-to-my-korean-readers-90-seconds"}, 477424},
|
||||
{{655173, "jp--0xbomwjkgm"}, 539940},
|
||||
{{655173, "ben-shapiro-jordan-peterson-and-a-12"}, 413749},
|
||||
{{655173, "jp-91jwsb7zyhw"}, 539940},
|
||||
{{655173, "deconstruction-the-lindsay-shepherd"}, 299272},
|
||||
{{655173, "september-patreon-q-a"}, 285451},
|
||||
{{655173, "jp-2c3m0tt5kce"}, 539940},
|
||||
{{655173, "australia-s-john-anderson-dr-jordan-b"}, 413749},
|
||||
{{655173, "jp-hdrlq7dpiws"}, 539940},
|
||||
{{655173, "stephen-hicks-postmodernism-reprise"}, 578480},
|
||||
{{655173, "october-patreon-q-a"}, 285451},
|
||||
{{655173, "an-animated-intro-to-truth-order-and"}, 413749},
|
||||
{{655173, "jp-bsh37-x5rny"}, 539940},
|
||||
{{655173, "january-2019-q-a"}, 503477},
|
||||
{{655173, "comedians-canaries-and-coalmines"}, 498586},
|
||||
{{655173, "the-democrats-apology-and-promise"}, 465433},
|
||||
{{655173, "jp-s4c-jodptn8"}, 539940},
|
||||
{{655173, "2014-personality-lecture-16-extraversion"}, 578465},
|
||||
{{655173, "dr-jordan-b-peterson-on-femsplainers"}, 490395},
|
||||
{{655173, "higher-ed-our-cultural-inflection-point"}, 527291},
|
||||
{{655173, "archetype-reality-friendship-and"}, 519736},
|
||||
{{655173, "sir-roger-scruton-dr-jordan-b-peterson"}, 490395},
|
||||
{{655173, "jp-cf2nqmqifxc"}, 539940},
|
||||
{{655173, "penguin-uk-12-rules-for-life"}, 413749},
|
||||
{{655173, "march-2019-q-and-a"}, 537138},
|
||||
{{655173, "jp-ne5vbomsqjc"}, 539940},
|
||||
{{655173, "dublin-london-harris-murray-new-usa-12"}, 413749},
|
||||
{{655173, "12-rules-12-cities-tickets-now-available"}, 413749},
|
||||
{{655173, "jp-j9j-bvdrgdi"}, 539940},
|
||||
{{655173, "responsibility-conscience-and-meaning"}, 499123},
|
||||
{{655173, "04-harris-murray-peterson-discussion"}, 436678},
|
||||
{{655173, "jp-ayhaz9k008q"}, 539940},
|
||||
{{655173, "with-jocko-willink-the-catastrophe-of"}, 490395},
|
||||
{{655173, "interview-with-the-grievance-studies"}, 501296},
|
||||
{{655173, "russell-brand-jordan-b-peterson-under"}, 413750},
|
||||
{{655173, "goodbye-to-patreon"}, 496771},
|
||||
{{655173, "revamped-podcast-announcement-with"}, 540943},
|
||||
{{655173, "swedes-want-to-know"}, 285453},
|
||||
{{655173, "auckland-clip-2-the-four-fundamental"}, 607892},
|
||||
{{655173, "jp-dtirzqmgbdm"}, 539940},
|
||||
{{655173, "political-correctness-a-force-for-good-a"}, 413750},
|
||||
{{655173, "sean-plunket-full-interview-new-zealand"}, 597638},
|
||||
{{655173, "q-a-the-meaning-and-reality-of"}, 616984},
|
||||
{{655173, "lecture-and-q-a-with-jordan-peterson-the"}, 413749},
|
||||
{{655173, "2017-personality-07-carl-jung-and-the"}, 578465},
|
||||
{{655173, "nina-paley-animator-extraordinaire"}, 413750},
|
||||
{{655173, "truth-as-the-antidote-to-suffering-with"}, 455127},
|
||||
{{655173, "bishop-barron-word-on-fire"}, 599814},
|
||||
{{655173, "zizek-vs-peterson-april-19"}, 527291},
|
||||
{{655173, "revamped-podcast-with-westwood-one"}, 540943},
|
||||
{{655173, "2016-11-19-university-of-toronto-free"}, 578465},
|
||||
{{655173, "jp-1emrmtrj5jc"}, 539940},
|
||||
{{655173, "who-is-joe-rogan-with-jordan-peterson"}, 585578},
|
||||
{{655173, "who-dares-say-he-believes-in-god"}, 581738},
|
||||
{{655252, "games-with-live2d"}, 589978},
|
||||
{{655252, "kaenbyou-rin-live2d"}, 589978},
|
||||
{{655374, "steam-groups-are-crazy"}, 607590},
|
||||
{{655379, "asmr-captain-falcon-happily-beats-you-up"}, 644574},
|
||||
{{655379, "pixel-art-series-5-link-holding-the"}, 442952},
|
||||
{{655379, "who-can-cross-the-planck-length-the-hero"}, 610830},
|
||||
{{655379, "ssbb-the-yoshi-grab-release-crash"}, 609747},
|
||||
{{655379, "tas-captain-falcon-s-bizarre-adventure"}, 442958},
|
||||
{{655379, "super-smash-bros-in-360-test"}, 442963},
|
||||
{{655379, "what-if-luigi-was-b-u-f-f"}, 442971},
|
||||
{{655803, "sun-time-lapse-test-7"}, 610634},
|
||||
{{655952, "upper-build-complete"}, 591728},
|
||||
{{656758, "cryptocurrency-awareness-adoption-the"}, 541770},
|
||||
{{656829, "3d-printing-technologies-comparison"}, 462685},
|
||||
{{656829, "3d-printing-for-everyone"}, 462685},
|
||||
{{657052, "tni-punya-ilmu-kanuragan-gaya-baru"}, 657045},
|
||||
{{657052, "papa-sunimah-nelpon-sri-utami-emon"}, 657045},
|
||||
{{657274, "rapforlife-4-win"}, 656856},
|
||||
{{657274, "bizzilion-proof-of-withdrawal"}, 656856},
|
||||
{{657420, "quick-drawing-prince-tribute-colored"}, 605630},
|
||||
{{657453, "white-boy-tom-mcdonald-facts"}, 597169},
|
||||
{{657453, "is-it-ok-to-look-when-you-with-your-girl"}, 610508},
|
||||
{{657584, "need-for-speed-ryzen-5-1600-gtx-1050-ti"}, 657161},
|
||||
{{657584, "quantum-break-ryzen-5-1600-gtx-1050-ti-4"}, 657161},
|
||||
{{657584, "nightcore-legends-never-die"}, 657161},
|
||||
{{657706, "mtb-enduro-ferragosto-2019-sestri"}, 638904},
|
||||
{{657706, "warface-free-for-all"}, 638908},
|
||||
{{657782, "nick-warren-at-loveland-but-not-really"}, 444299},
|
||||
{{658098, "le-temps-nous-glisse-entre-les-doigts"}, 600099},
|
||||
};
|
||||
|
||||
#endif // TAKEOVERWORKAROUNDS_H
|
||||
@@ -1,953 +0,0 @@
|
||||
|
||||
#include <forks.h>
|
||||
#include <hashes.h>
|
||||
#include <log.h>
|
||||
#include <sqlite.h>
|
||||
#include <trie.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
|
||||
#define logPrint CLogPrint::global()
|
||||
|
||||
static const auto one = uint256S("0000000000000000000000000000000000000000000000000000000000000001");
|
||||
|
||||
std::vector<unsigned char> heightToVch(int n)
|
||||
{
|
||||
std::vector<uint8_t> vchHeight(8, 0);
|
||||
vchHeight[4] = n >> 24;
|
||||
vchHeight[5] = n >> 16;
|
||||
vchHeight[6] = n >> 8;
|
||||
vchHeight[7] = n;
|
||||
return vchHeight;
|
||||
}
|
||||
|
||||
uint256 getValueHash(const COutPoint& outPoint, int nHeightOfLastTakeover)
|
||||
{
|
||||
auto hash1 = Hash(outPoint.hash.begin(), outPoint.hash.end());
|
||||
auto snOut = std::to_string(outPoint.n);
|
||||
auto hash2 = Hash(snOut.begin(), snOut.end());
|
||||
auto vchHash = heightToVch(nHeightOfLastTakeover);
|
||||
auto hash3 = Hash(vchHash.begin(), vchHash.end());
|
||||
return Hash(hash1.begin(), hash1.end(), hash2.begin(), hash2.end(), hash3.begin(), hash3.end());
|
||||
}
|
||||
|
||||
static const sqlite::sqlite_config sharedConfig {
|
||||
sqlite::OpenFlags::READWRITE | sqlite::OpenFlags::CREATE,
|
||||
nullptr, sqlite::Encoding::UTF8
|
||||
};
|
||||
|
||||
void applyPragmas(sqlite::database& db, std::size_t cache)
|
||||
{
|
||||
db << "PRAGMA cache_size=-" + std::to_string(cache); // in -KB
|
||||
db << "PRAGMA synchronous=OFF"; // don't disk sync after transaction commit
|
||||
db << "PRAGMA journal_mode=WAL";
|
||||
db << "PRAGMA temp_store=MEMORY";
|
||||
db << "PRAGMA case_sensitive_like=true";
|
||||
|
||||
db.define("POPS", [](std::string s) -> std::string { if (!s.empty()) s.pop_back(); return s; });
|
||||
db.define("REVERSE", [](std::vector<uint8_t> s) -> std::vector<uint8_t> { std::reverse(s.begin(), s.end()); return s; });
|
||||
}
|
||||
|
||||
CClaimTrie::CClaimTrie(std::size_t cacheBytes, bool fWipe, int height,
|
||||
const std::string& dataDir,
|
||||
int nNormalizedNameForkHeight,
|
||||
int nMinRemovalWorkaroundHeight,
|
||||
int nMaxRemovalWorkaroundHeight,
|
||||
int64_t nOriginalClaimExpirationTime,
|
||||
int64_t nExtendedClaimExpirationTime,
|
||||
int64_t nExtendedClaimExpirationForkHeight,
|
||||
int64_t nAllClaimsInMerkleForkHeight,
|
||||
int proportionalDelayFactor) :
|
||||
nNextHeight(height),
|
||||
dbCacheBytes(cacheBytes),
|
||||
dbFile(dataDir + "/claims.sqlite"), db(dbFile, sharedConfig),
|
||||
nProportionalDelayFactor(proportionalDelayFactor),
|
||||
nNormalizedNameForkHeight(nNormalizedNameForkHeight),
|
||||
nMinRemovalWorkaroundHeight(nMinRemovalWorkaroundHeight),
|
||||
nMaxRemovalWorkaroundHeight(nMaxRemovalWorkaroundHeight),
|
||||
nOriginalClaimExpirationTime(nOriginalClaimExpirationTime),
|
||||
nExtendedClaimExpirationTime(nExtendedClaimExpirationTime),
|
||||
nExtendedClaimExpirationForkHeight(nExtendedClaimExpirationForkHeight),
|
||||
nAllClaimsInMerkleForkHeight(nAllClaimsInMerkleForkHeight)
|
||||
{
|
||||
applyPragmas(db, 5U * 1024U); // in KB
|
||||
|
||||
db << "CREATE TABLE IF NOT EXISTS node (name BLOB NOT NULL PRIMARY KEY, "
|
||||
"parent BLOB REFERENCES node(name) DEFERRABLE INITIALLY DEFERRED, "
|
||||
"hash BLOB)";
|
||||
|
||||
db << "CREATE TABLE IF NOT EXISTS claim (claimID BLOB NOT NULL PRIMARY KEY, name BLOB NOT NULL, "
|
||||
"nodeName BLOB NOT NULL REFERENCES node(name) DEFERRABLE INITIALLY DEFERRED, "
|
||||
"txID BLOB NOT NULL, txN INTEGER NOT NULL, originalHeight INTEGER NOT NULL, updateHeight INTEGER NOT NULL, "
|
||||
"validHeight INTEGER NOT NULL, activationHeight INTEGER NOT NULL, "
|
||||
"expirationHeight INTEGER NOT NULL, amount INTEGER NOT NULL);";
|
||||
|
||||
db << "CREATE TABLE IF NOT EXISTS support (txID BLOB NOT NULL, txN INTEGER NOT NULL, "
|
||||
"supportedClaimID BLOB NOT NULL, name BLOB NOT NULL, nodeName BLOB NOT NULL, "
|
||||
"blockHeight INTEGER NOT NULL, validHeight INTEGER NOT NULL, activationHeight INTEGER NOT NULL, "
|
||||
"expirationHeight INTEGER NOT NULL, amount INTEGER NOT NULL, PRIMARY KEY(txID, txN));";
|
||||
|
||||
db << "CREATE TABLE IF NOT EXISTS takeover (name BLOB NOT NULL, height INTEGER NOT NULL, "
|
||||
"claimID BLOB, PRIMARY KEY(name, height DESC));";
|
||||
|
||||
if (fWipe) {
|
||||
db << "DELETE FROM node";
|
||||
db << "DELETE FROM claim";
|
||||
db << "DELETE FROM support";
|
||||
db << "DELETE FROM takeover";
|
||||
}
|
||||
|
||||
db << "CREATE INDEX IF NOT EXISTS node_hash_len_name ON node (hash, LENGTH(name) DESC)";
|
||||
// db << "CREATE UNIQUE INDEX IF NOT EXISTS node_parent_name ON node (parent, name)"; // no apparent gain
|
||||
db << "CREATE INDEX IF NOT EXISTS node_parent ON node (parent)";
|
||||
|
||||
db << "CREATE INDEX IF NOT EXISTS takeover_height ON takeover (height)";
|
||||
|
||||
db << "CREATE INDEX IF NOT EXISTS claim_activationHeight ON claim (activationHeight)";
|
||||
db << "CREATE INDEX IF NOT EXISTS claim_expirationHeight ON claim (expirationHeight)";
|
||||
db << "CREATE INDEX IF NOT EXISTS claim_nodeName ON claim (nodeName)";
|
||||
|
||||
db << "CREATE INDEX IF NOT EXISTS support_supportedClaimID ON support (supportedClaimID)";
|
||||
db << "CREATE INDEX IF NOT EXISTS support_activationHeight ON support (activationHeight)";
|
||||
db << "CREATE INDEX IF NOT EXISTS support_expirationHeight ON support (expirationHeight)";
|
||||
db << "CREATE INDEX IF NOT EXISTS support_nodeName ON support (nodeName)";
|
||||
|
||||
db << "INSERT OR IGNORE INTO node(name, hash) VALUES(x'', ?)" << one; // ensure that we always have our root node
|
||||
}
|
||||
|
||||
CClaimTrieCacheBase::~CClaimTrieCacheBase()
|
||||
{
|
||||
if (transacting) {
|
||||
db << "ROLLBACK";
|
||||
transacting = false;
|
||||
}
|
||||
claimHashQuery.used(true);
|
||||
childHashQuery.used(true);
|
||||
claimHashQueryLimit.used(true);
|
||||
}
|
||||
|
||||
bool CClaimTrie::SyncToDisk()
|
||||
{
|
||||
// alternatively, switch to full sync after we are caught up on the chain
|
||||
auto rc = sqlite3_wal_checkpoint_v2(db.connection().get(), nullptr, SQLITE_CHECKPOINT_FULL, nullptr, nullptr);
|
||||
return rc == SQLITE_OK;
|
||||
}
|
||||
|
||||
bool CClaimTrie::empty()
|
||||
{
|
||||
int64_t count;
|
||||
db << "SELECT COUNT(*) FROM (SELECT 1 FROM claim WHERE activationHeight < ?1 AND expirationHeight >= ?1 LIMIT 1)" << nNextHeight >> count;
|
||||
return count == 0;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::haveClaim(const std::string& name, const COutPoint& outPoint) const
|
||||
{
|
||||
auto query = db << "SELECT 1 FROM claim WHERE nodeName = ?1 AND txID = ?2 AND txN = ?3 "
|
||||
"AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1"
|
||||
<< name << outPoint.hash << outPoint.n << nNextHeight;
|
||||
return query.begin() != query.end();
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::haveSupport(const std::string& name, const COutPoint& outPoint) const
|
||||
{
|
||||
auto query = db << "SELECT 1 FROM support WHERE nodeName = ?1 AND txID = ?2 AND txN = ?3 "
|
||||
"AND activationHeight < ?4 AND expirationHeight >= ?4 LIMIT 1"
|
||||
<< name << outPoint.hash << outPoint.n << nNextHeight;
|
||||
return query.begin() != query.end();
|
||||
}
|
||||
|
||||
supportEntryType CClaimTrieCacheBase::getSupportsForName(const std::string& name) const
|
||||
{
|
||||
// includes values that are not yet valid
|
||||
auto query = db << "SELECT supportedClaimID, txID, txN, blockHeight, activationHeight, amount "
|
||||
"FROM support WHERE nodeName = ? AND expirationHeight >= ?" << name << nNextHeight;
|
||||
supportEntryType ret;
|
||||
for (auto&& row: query) {
|
||||
CSupportValue value;
|
||||
row >> value.supportedClaimId >> value.outPoint.hash >> value.outPoint.n
|
||||
>> value.nHeight >> value.nValidAtHeight >> value.nAmount;
|
||||
ret.push_back(std::move(value));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
|
||||
{
|
||||
auto query = db << "SELECT activationHeight FROM claim WHERE nodeName = ? AND txID = ? AND txN = ? "
|
||||
"AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1"
|
||||
<< name << outPoint.hash << outPoint.n << nNextHeight;
|
||||
for (auto&& row: query) {
|
||||
row >> nValidAtHeight;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const
|
||||
{
|
||||
auto query = db << "SELECT activationHeight FROM support WHERE nodeName = ? AND txID = ? AND txN = ? "
|
||||
"AND activationHeight >= ? AND expirationHeight >= activationHeight LIMIT 1"
|
||||
<< name << outPoint.hash << outPoint.n << nNextHeight;
|
||||
for (auto&& row: query) {
|
||||
row >> nValidAtHeight;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::deleteNodeIfPossible(const std::string& name, std::string& parent, int64_t& claims)
|
||||
{
|
||||
if (name.empty()) return false;
|
||||
// to remove a node it must have one or less children and no claims
|
||||
db << "SELECT COUNT(*) FROM (SELECT 1 FROM claim WHERE nodeName = ?1 AND activationHeight < ?2 AND expirationHeight >= ?2 LIMIT 1)"
|
||||
<< name << nNextHeight >> claims;
|
||||
if (claims > 0) return false; // still has claims
|
||||
// we now know it has no claims, but we need to check its children
|
||||
int64_t count;
|
||||
std::string childName;
|
||||
// this line assumes that we've set the parent on child nodes already,
|
||||
// which means we are len(name) desc in our parent method
|
||||
db << "SELECT COUNT(*), MAX(name) FROM node WHERE parent = ?" << name >> std::tie(count, childName);
|
||||
if (count > 1) return false; // still has multiple children
|
||||
logPrint << "Removing node " << name << " with " << count << " children" << Clog::endl;
|
||||
// okay. it's going away
|
||||
auto query = db << "SELECT parent FROM node WHERE name = ?" << name;
|
||||
auto it = query.begin();
|
||||
if (it == query.end())
|
||||
return true; // we'll assume that whoever deleted this node previously cleaned things up correctly
|
||||
*it >> parent;
|
||||
db << "DELETE FROM node WHERE name = ?" << name;
|
||||
auto ret = db.rows_modified() > 0;
|
||||
if (ret && count == 1) // make the child skip us and point to its grandparent:
|
||||
db << "UPDATE node SET parent = ? WHERE name = ?" << parent << childName;
|
||||
if (ret)
|
||||
db << "UPDATE node SET hash = NULL WHERE name = ?" << parent;
|
||||
return ret;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheBase::ensureTreeStructureIsUpToDate()
|
||||
{
|
||||
if (!transacting) return;
|
||||
|
||||
// your children are your nodes that match your key but go at least one longer,
|
||||
// and have no trailing prefix in common with the other nodes in that set -- a hard query w/o parent field
|
||||
|
||||
// when we get into this method, we have some claims that have been added, removed, and updated
|
||||
// those each have a corresponding node in the list with a null hash
|
||||
// some of our nodes will go away, some new ones will be added, some will be reparented
|
||||
|
||||
|
||||
// the plan: update all the claim hashes first
|
||||
std::vector<std::string> names;
|
||||
db << "SELECT name FROM node WHERE hash IS NULL"
|
||||
>> [&names](std::string name) {
|
||||
names.push_back(std::move(name));
|
||||
};
|
||||
if (names.empty()) return; // nothing to do
|
||||
std::sort(names.begin(), names.end()); // guessing this is faster than "ORDER BY name"
|
||||
|
||||
// there's an assumption that all nodes with claims are here; we do that as claims are inserted
|
||||
|
||||
// assume parents are not set correctly here:
|
||||
auto parentQuery = db << "SELECT MAX(name) FROM node WHERE "
|
||||
"name IN (WITH RECURSIVE prefix(p) AS (VALUES(?) UNION ALL "
|
||||
"SELECT POPS(p) FROM prefix WHERE p != x'') SELECT p FROM prefix)";
|
||||
|
||||
auto insertQuery = db << "INSERT INTO node(name, parent, hash) VALUES(?, ?, NULL) "
|
||||
"ON CONFLICT(name) DO UPDATE SET parent = excluded.parent, hash = NULL";
|
||||
|
||||
auto nodeQuery = db << "SELECT name FROM node WHERE parent = ?";
|
||||
auto updateQuery = db << "UPDATE node SET parent = ? WHERE name = ?";
|
||||
|
||||
for (auto& name: names) {
|
||||
int64_t claims;
|
||||
std::string parent, node;
|
||||
for (node = name; deleteNodeIfPossible(node, parent, claims);)
|
||||
node = parent;
|
||||
if (node != name || name.empty() || claims <= 0)
|
||||
continue; // if you have no claims but we couldn't delete you, you must have legitimate children
|
||||
|
||||
parentQuery << name.substr(0, name.size() - 1);
|
||||
auto queryIt = parentQuery.begin();
|
||||
if (queryIt != parentQuery.end())
|
||||
*queryIt >> parent;
|
||||
else
|
||||
parent.clear();
|
||||
parentQuery++; // reusing knocks off about 10% of the query time
|
||||
|
||||
// we know now that we need to insert it,
|
||||
// but we may need to insert a parent node for it first (also called a split)
|
||||
const auto psize = parent.size() + 1;
|
||||
for (auto&& row : nodeQuery << parent) {
|
||||
std::string sibling; row >> sibling;
|
||||
if (sibling.compare(0, psize, name, 0, psize) != 0)
|
||||
continue;
|
||||
auto splitPos = psize;
|
||||
while(splitPos < sibling.size() && splitPos < name.size() && sibling[splitPos] == name[splitPos])
|
||||
++splitPos;
|
||||
auto newNodeName = name.substr(0, splitPos);
|
||||
// update the to-be-fostered sibling:
|
||||
updateQuery << newNodeName << sibling;
|
||||
updateQuery++;
|
||||
if (splitPos == name.size())
|
||||
// our new node is the same as the one we wanted to insert
|
||||
break;
|
||||
// insert the split node:
|
||||
logPrint << "Inserting split node " << newNodeName << " near " << sibling << ", parent " << parent << Clog::endl;
|
||||
insertQuery << newNodeName << parent;
|
||||
insertQuery++;
|
||||
|
||||
parent = std::move(newNodeName);
|
||||
break;
|
||||
}
|
||||
nodeQuery++;
|
||||
|
||||
logPrint << "Inserting or updating node " << name << ", parent " << parent << Clog::endl;
|
||||
insertQuery << name << parent;
|
||||
insertQuery++;
|
||||
}
|
||||
|
||||
nodeQuery.used(true);
|
||||
updateQuery.used(true);
|
||||
parentQuery.used(true);
|
||||
insertQuery.used(true);
|
||||
|
||||
// now we need to percolate the nulls up the tree
|
||||
// parents should all be set right
|
||||
db << "UPDATE node SET hash = NULL WHERE name IN (WITH RECURSIVE prefix(p) AS "
|
||||
"(SELECT parent FROM node WHERE hash IS NULL UNION SELECT parent FROM prefix, node "
|
||||
"WHERE name = prefix.p AND prefix.p != x'') SELECT p FROM prefix)";
|
||||
}
|
||||
|
||||
std::size_t CClaimTrieCacheBase::getTotalNamesInTrie() const
|
||||
{
|
||||
// you could do this select from the node table, but you would have to ensure it is not dirty first
|
||||
std::size_t ret;
|
||||
db << "SELECT COUNT(DISTINCT nodeName) FROM claim WHERE activationHeight < ?1 AND expirationHeight >= ?1"
|
||||
<< nNextHeight >> ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::size_t CClaimTrieCacheBase::getTotalClaimsInTrie() const
|
||||
{
|
||||
std::size_t ret;
|
||||
db << "SELECT COUNT(*) FROM claim WHERE activationHeight < ?1 AND expirationHeight >= ?1"
|
||||
<< nNextHeight >> ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
int64_t CClaimTrieCacheBase::getTotalValueOfClaimsInTrie(bool fControllingOnly) const
|
||||
{
|
||||
int64_t ret = 0;
|
||||
const std::string query = fControllingOnly ?
|
||||
"SELECT SUM(amount) FROM (SELECT c.amount as amount, "
|
||||
"(SELECT(SELECT IFNULL(SUM(s.amount),0)+c.amount FROM support s "
|
||||
"WHERE s.supportedClaimID = c.claimID AND c.nodeName = s.nodeName "
|
||||
"AND s.activationHeight < ?1 AND s.expirationHeight >= ?1) as effective "
|
||||
"ORDER BY effective DESC LIMIT 1) as winner FROM claim c "
|
||||
"WHERE c.activationHeight < ?1 AND c.expirationHeight >= ?1 GROUP BY c.nodeName)"
|
||||
:
|
||||
"SELECT SUM(amount) FROM (SELECT c.amount as amount "
|
||||
"FROM claim c WHERE c.activationHeight < ?1 AND c.expirationHeight >= ?1)";
|
||||
|
||||
db << query << nNextHeight >> ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset) const
|
||||
{
|
||||
auto ret = false;
|
||||
auto nextHeight = nNextHeight + heightOffset;
|
||||
for (auto&& row: claimHashQueryLimit << nextHeight << name) {
|
||||
row >> claim.outPoint.hash >> claim.outPoint.n >> claim.claimId
|
||||
>> claim.nHeight >> claim.nValidAtHeight >> claim.nAmount >> claim.nEffectiveAmount;
|
||||
ret = true;
|
||||
break;
|
||||
}
|
||||
claimHashQueryLimit++;
|
||||
return ret;
|
||||
}
|
||||
|
||||
CClaimSupportToName CClaimTrieCacheBase::getClaimsForName(const std::string& name) const
|
||||
{
|
||||
uint160 claimId;
|
||||
int nLastTakeoverHeight = 0;
|
||||
getLastTakeoverForName(name, claimId, nLastTakeoverHeight);
|
||||
|
||||
auto supports = getSupportsForName(name);
|
||||
auto find = [&supports](decltype(supports)::iterator& it, const CClaimValue& claim) {
|
||||
it = std::find_if(it, supports.end(), [&claim](const CSupportValue& support) {
|
||||
return claim.claimId == support.supportedClaimId;
|
||||
});
|
||||
return it != supports.end();
|
||||
};
|
||||
|
||||
auto query = db << "SELECT claimID, txID, txN, originalHeight, updateHeight, activationHeight, amount "
|
||||
"FROM claim WHERE nodeName = ? AND expirationHeight >= ?"
|
||||
<< name << nNextHeight;
|
||||
|
||||
// match support to claim
|
||||
std::vector<CClaimNsupports> claimsNsupports;
|
||||
for (auto &&row: query) {
|
||||
CClaimValue claim;
|
||||
int originalHeight;
|
||||
row >> claim.claimId >> claim.outPoint.hash >> claim.outPoint.n
|
||||
>> originalHeight >> claim.nHeight >> claim.nValidAtHeight >> claim.nAmount;
|
||||
int64_t nAmount = claim.nValidAtHeight < nNextHeight ? claim.nAmount : 0;
|
||||
auto ic = claimsNsupports.emplace(claimsNsupports.end(), claim, nAmount, originalHeight);
|
||||
for (auto it = supports.begin(); find(it, claim); it = supports.erase(it)) {
|
||||
if (it->nValidAtHeight < nNextHeight)
|
||||
ic->effectiveAmount += it->nAmount;
|
||||
ic->supports.push_back(std::move(*it));
|
||||
}
|
||||
ic->claim.nEffectiveAmount = ic->effectiveAmount;
|
||||
}
|
||||
std::sort(claimsNsupports.rbegin(), claimsNsupports.rend());
|
||||
return {name, nLastTakeoverHeight, std::move(claimsNsupports), std::move(supports)};
|
||||
}
|
||||
|
||||
void completeHash(uint256& partialHash, const std::string& key, int to)
|
||||
{
|
||||
for (auto it = key.rbegin(); std::distance(it, key.rend()) > to + 1; ++it)
|
||||
partialHash = Hash(it, it + 1, partialHash.begin(), partialHash.end());
|
||||
}
|
||||
|
||||
uint256 CClaimTrieCacheBase::computeNodeHash(const std::string& name, int takeoverHeight)
|
||||
{
|
||||
const auto pos = name.size();
|
||||
std::vector<uint8_t> vchToHash;
|
||||
// we have to free up the hash query so it can be reused by a child
|
||||
childHashQuery << name >> [&vchToHash, pos](std::string name, uint256 hash) {
|
||||
completeHash(hash, name, pos);
|
||||
vchToHash.push_back(name[pos]);
|
||||
vchToHash.insert(vchToHash.end(), hash.begin(), hash.end());
|
||||
};
|
||||
childHashQuery++;
|
||||
|
||||
CClaimValue claim;
|
||||
if (getInfoForName(name, claim)) {
|
||||
auto valueHash = getValueHash(claim.outPoint, takeoverHeight);
|
||||
vchToHash.insert(vchToHash.end(), valueHash.begin(), valueHash.end());
|
||||
}
|
||||
|
||||
return vchToHash.empty() ? one : Hash(vchToHash.begin(), vchToHash.end());
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::checkConsistency()
|
||||
{
|
||||
// verify that all claims hash to the values on the nodes
|
||||
|
||||
auto query = db << "SELECT n.name, n.hash, "
|
||||
"IFNULL((SELECT CASE WHEN t.claimID IS NULL THEN 0 ELSE t.height END "
|
||||
"FROM takeover t WHERE t.name = n.name ORDER BY t.height DESC LIMIT 1), 0) FROM node n";
|
||||
for (auto&& row: query) {
|
||||
std::string name;
|
||||
uint256 hash;
|
||||
int takeoverHeight;
|
||||
row >> name >> hash >> takeoverHeight;
|
||||
auto computedHash = computeNodeHash(name, takeoverHeight);
|
||||
if (computedHash != hash)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::validateDb(int height, const uint256& rootHash)
|
||||
{
|
||||
base->nNextHeight = nNextHeight = height + 1;
|
||||
|
||||
if (checkConsistency()) {
|
||||
if (rootHash != getMerkleHash()) {
|
||||
logPrint << "CClaimTrieCacheBase::" << __func__ << "(): the block's root claim hash doesn't match the persisted claim root hash." << Clog::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (nNextHeight > base->nAllClaimsInMerkleForkHeight) // index not used as part of sync:
|
||||
db << "CREATE UNIQUE INDEX IF NOT EXISTS claim_reverseClaimID ON claim (REVERSE(claimID))";
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::flush()
|
||||
{
|
||||
if (transacting) {
|
||||
getMerkleHash();
|
||||
auto code = sqlite::commit(db);
|
||||
if (code != SQLITE_OK) {
|
||||
logPrint << "ERROR in CClaimTrieCacheBase::" << __func__ << "(): SQLite code: " << code << Clog::endl;
|
||||
return false;
|
||||
}
|
||||
transacting = false;
|
||||
}
|
||||
base->nNextHeight = nNextHeight;
|
||||
removalWorkaround.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::string childHashQuery_s = "SELECT name, hash FROM node WHERE parent = ? ORDER BY name";
|
||||
|
||||
const std::string claimHashQuery_s =
|
||||
"SELECT c.txID, c.txN, c.claimID, c.updateHeight, c.activationHeight, c.amount, "
|
||||
"(SELECT IFNULL(SUM(s.amount),0)+c.amount FROM support s "
|
||||
"WHERE s.supportedClaimID = c.claimID AND s.nodeName = c.nodeName "
|
||||
"AND s.activationHeight < ?1 AND s.expirationHeight >= ?1) as effectiveAmount "
|
||||
"FROM claim c WHERE c.nodeName = ?2 AND c.activationHeight < ?1 AND c.expirationHeight >= ?1 "
|
||||
"ORDER BY effectiveAmount DESC, c.updateHeight, c.txID, c.txN";
|
||||
|
||||
const std::string claimHashQueryLimit_s = claimHashQuery_s + " LIMIT 1";
|
||||
|
||||
extern const std::string proofClaimQuery_s =
|
||||
"SELECT n.name, IFNULL((SELECT CASE WHEN t.claimID IS NULL THEN 0 ELSE t.height END "
|
||||
"FROM takeover t WHERE t.name = n.name ORDER BY t.height DESC LIMIT 1), 0) FROM node n "
|
||||
"WHERE n.name IN (WITH RECURSIVE prefix(p) AS (VALUES(?) UNION ALL "
|
||||
"SELECT POPS(p) FROM prefix WHERE p != x'') SELECT p FROM prefix) "
|
||||
"ORDER BY n.name";
|
||||
|
||||
CClaimTrieCacheBase::CClaimTrieCacheBase(CClaimTrie* base)
|
||||
: base(base), db(base->dbFile, sharedConfig), transacting(false),
|
||||
childHashQuery(db << childHashQuery_s),
|
||||
claimHashQuery(db << claimHashQuery_s),
|
||||
claimHashQueryLimit(db << claimHashQueryLimit_s)
|
||||
{
|
||||
assert(base);
|
||||
nNextHeight = base->nNextHeight;
|
||||
|
||||
applyPragmas(db, base->dbCacheBytes >> 10U); // in KB
|
||||
}
|
||||
|
||||
void CClaimTrieCacheBase::ensureTransacting()
|
||||
{
|
||||
if (!transacting) {
|
||||
transacting = true;
|
||||
db << "BEGIN";
|
||||
}
|
||||
}
|
||||
|
||||
int CClaimTrieCacheBase::expirationTime() const
|
||||
{
|
||||
return base->nOriginalClaimExpirationTime;
|
||||
}
|
||||
|
||||
uint256 CClaimTrieCacheBase::getMerkleHash()
|
||||
{
|
||||
ensureTreeStructureIsUpToDate();
|
||||
uint256 hash;
|
||||
db << "SELECT hash FROM node WHERE name = x''"
|
||||
>> [&hash](std::unique_ptr<uint256> rootHash) {
|
||||
if (rootHash)
|
||||
hash = std::move(*rootHash);
|
||||
};
|
||||
if (!hash.IsNull())
|
||||
return hash;
|
||||
assert(transacting); // no data changed but we didn't have the root hash there already?
|
||||
auto updateQuery = db << "UPDATE node SET hash = ? WHERE name = ?";
|
||||
db << "SELECT n.name, IFNULL((SELECT CASE WHEN t.claimID IS NULL THEN 0 ELSE t.height END FROM takeover t WHERE t.name = n.name "
|
||||
"ORDER BY t.height DESC LIMIT 1), 0) FROM node n WHERE n.hash IS NULL ORDER BY LENGTH(n.name) DESC" // assumes n.name is blob
|
||||
>> [this, &hash, &updateQuery](const std::string& name, int takeoverHeight) {
|
||||
hash = computeNodeHash(name, takeoverHeight);
|
||||
updateQuery << hash << name;
|
||||
updateQuery++;
|
||||
};
|
||||
updateQuery.used(true);
|
||||
return hash;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::getLastTakeoverForName(const std::string& name, uint160& claimId, int& takeoverHeight) const
|
||||
{
|
||||
auto query = db << "SELECT t.height, t.claimID FROM takeover t "
|
||||
"WHERE t.name = ?1 ORDER BY t.height DESC LIMIT 1" << name;
|
||||
auto it = query.begin();
|
||||
if (it != query.end()) {
|
||||
std::unique_ptr<uint160> claimIdOrNull;
|
||||
*it >> takeoverHeight >> claimIdOrNull;
|
||||
if (claimIdOrNull) {
|
||||
claimId = *claimIdOrNull;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::addClaim(const std::string& name, const COutPoint& outPoint, const uint160& claimId,
|
||||
int64_t nAmount, int nHeight, int nValidHeight, int originalHeight)
|
||||
{
|
||||
ensureTransacting();
|
||||
|
||||
// in the update scenario the previous one should be removed already
|
||||
// in the downgrade scenario, the one ahead will be removed already and the old one's valid height is input
|
||||
// revisiting the update scenario we have two options:
|
||||
// 1. let them pull the old one first, in which case they will be responsible to pass in validHeight (since we can't determine it's a 0 delay)
|
||||
// 2. don't remove the old one; have this method do a kinder "update" situation.
|
||||
// Option 2 has the issue in that we don't actually update if we don't have an existing match,
|
||||
// and no way to know that here without an 'update' flag
|
||||
// In addition, as we currently do option 1 they use that to get the old valid height and store that for undo
|
||||
// We would have to make this method return that if we go without the removal
|
||||
// The other problem with 1 is that the outer shell would need to know if the one they removed was a winner or not
|
||||
|
||||
if (nValidHeight <= 0)
|
||||
nValidHeight = nHeight + getDelayForName(name, claimId); // sets nValidHeight to the old value
|
||||
|
||||
if (originalHeight <= 0)
|
||||
originalHeight = nHeight;
|
||||
|
||||
auto nodeName = adjustNameForValidHeight(name, nValidHeight);
|
||||
auto expires = expirationTime() + nHeight;
|
||||
|
||||
db << "INSERT INTO claim(claimID, name, nodeName, txID, txN, amount, originalHeight, updateHeight, "
|
||||
"validHeight, activationHeight, expirationHeight) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
<< claimId << name << nodeName << outPoint.hash << outPoint.n << nAmount
|
||||
<< originalHeight << nHeight << nValidHeight << nValidHeight << expires;
|
||||
|
||||
if (nValidHeight < nNextHeight)
|
||||
db << "INSERT INTO node(name) VALUES(?) ON CONFLICT(name) DO UPDATE SET hash = NULL" << nodeName;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::addSupport(const std::string& name, const COutPoint& outPoint, const uint160& supportedClaimId,
|
||||
int64_t nAmount, int nHeight, int nValidHeight)
|
||||
{
|
||||
ensureTransacting();
|
||||
|
||||
if (nValidHeight < 0)
|
||||
nValidHeight = nHeight + getDelayForName(name, supportedClaimId);
|
||||
|
||||
auto nodeName = adjustNameForValidHeight(name, nValidHeight);
|
||||
auto expires = expirationTime() + nHeight;
|
||||
|
||||
db << "INSERT INTO support(supportedClaimID, name, nodeName, txID, txN, amount, blockHeight, validHeight, activationHeight, expirationHeight) "
|
||||
"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
<< supportedClaimId << name << nodeName << outPoint.hash << outPoint.n << nAmount << nHeight << nValidHeight << nValidHeight << expires;
|
||||
|
||||
if (nValidHeight < nNextHeight)
|
||||
db << "UPDATE node SET hash = NULL WHERE name = ?" << nodeName;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::removeClaim(const uint160& claimId, const COutPoint& outPoint, std::string& nodeName,
|
||||
int& validHeight, int& originalHeight)
|
||||
{
|
||||
// this gets tricky in that we may be removing an update
|
||||
// when going forward we spend a claim (aka, call removeClaim) before updating it (aka, call addClaim)
|
||||
// when going backwards we first remove the update by calling removeClaim
|
||||
// we then undo the spend of the previous one by calling addClaim with the original data
|
||||
// in order to maintain the proper takeover height the updater will need to use our height returned here
|
||||
|
||||
{
|
||||
auto query = db << "SELECT nodeName, originalHeight, activationHeight FROM claim "
|
||||
"WHERE claimID = ? AND txID = ? AND txN = ? AND expirationHeight >= ?"
|
||||
<< claimId << outPoint.hash << outPoint.n << nNextHeight;
|
||||
auto it = query.begin();
|
||||
if (it == query.end())
|
||||
return false;
|
||||
|
||||
*it >> nodeName >> originalHeight >> validHeight;
|
||||
}
|
||||
ensureTransacting();
|
||||
|
||||
db << "DELETE FROM claim WHERE claimID = ? AND txID = ? AND txN = ?"
|
||||
<< claimId << outPoint.hash << outPoint.n;
|
||||
if (!db.rows_modified())
|
||||
return false;
|
||||
|
||||
db << "UPDATE node SET hash = NULL WHERE name = ?" << nodeName;
|
||||
|
||||
// when node should be deleted from cache but instead it's kept
|
||||
// because it's a parent one and should not be effectively erased
|
||||
// we had a bug in the old code where that situation would force a zero delay on re-add
|
||||
if (nNextHeight >= base->nMinRemovalWorkaroundHeight
|
||||
&& nNextHeight < base->nMaxRemovalWorkaroundHeight) { // TODO: hard fork this out (which we already tried once but failed)
|
||||
// neither LIKE nor SUBSTR will use an index on a blob, but BETWEEN is a good, fast alternative
|
||||
auto end = nodeName + std::string( 256, std::numeric_limits<char>::max()); // 256 == MAX_CLAIM_NAME_SIZE + 1
|
||||
auto innerQuery = db << "SELECT nodeName FROM claim WHERE nodeName BETWEEN ?1 AND ?2 "
|
||||
"AND activationHeight < ?3 AND expirationHeight >= ?3 ORDER BY nodeName LIMIT 1"
|
||||
<< nodeName << end << nNextHeight;
|
||||
for (auto&& row: innerQuery) {
|
||||
std::string shortestMatch;
|
||||
row >> shortestMatch;
|
||||
if (shortestMatch != nodeName)
|
||||
// set this when there are no more claims on that name and that node still has children
|
||||
removalWorkaround.insert(nodeName);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::removeSupport(const COutPoint& outPoint, std::string& nodeName, int& validHeight)
|
||||
{
|
||||
{
|
||||
auto query = db << "SELECT nodeName, activationHeight FROM support "
|
||||
"WHERE txID = ? AND txN = ? AND expirationHeight >= ?"
|
||||
<< outPoint.hash << outPoint.n << nNextHeight;
|
||||
auto it = query.begin();
|
||||
if (it == query.end())
|
||||
return false;
|
||||
|
||||
*it >> nodeName >> validHeight;
|
||||
}
|
||||
ensureTransacting();
|
||||
|
||||
db << "DELETE FROM support WHERE txID = ? AND txN = ?" << outPoint.hash << outPoint.n;
|
||||
if (!db.rows_modified())
|
||||
return false;
|
||||
db << "UPDATE node SET hash = NULL WHERE name = ?" << nodeName;
|
||||
return true;
|
||||
}
|
||||
|
||||
// hardcoded claims that should trigger a takeover
|
||||
#include <takeoverworkarounds.h>
|
||||
|
||||
bool CClaimTrieCacheBase::incrementBlock()
|
||||
{
|
||||
// the plan:
|
||||
// for every claim and support that becomes active this block set its node hash to null (aka, dirty)
|
||||
// for every claim and support that expires this block set its node hash to null and add it to the expire(Support)Undo
|
||||
// for all dirty nodes look for new takeovers
|
||||
ensureTransacting();
|
||||
|
||||
db << "INSERT INTO node(name) SELECT nodeName FROM claim INDEXED BY claim_activationHeight "
|
||||
"WHERE activationHeight = ?1 AND expirationHeight > ?1 "
|
||||
"ON CONFLICT(name) DO UPDATE SET hash = NULL"
|
||||
<< nNextHeight;
|
||||
|
||||
// don't make new nodes for items in supports or items that expire this block that don't exist in claims
|
||||
db << "UPDATE node SET hash = NULL WHERE name IN "
|
||||
"(SELECT nodeName FROM claim WHERE expirationHeight = ?1 "
|
||||
"UNION SELECT nodeName FROM support WHERE expirationHeight = ?1 OR activationHeight = ?1)"
|
||||
<< nNextHeight;
|
||||
|
||||
auto insertTakeoverQuery = db << "INSERT INTO takeover(name, height, claimID) VALUES(?, ?, ?)";
|
||||
|
||||
// takeover handling:
|
||||
db << "SELECT name FROM node WHERE hash IS NULL"
|
||||
>> [this, &insertTakeoverQuery](const std::string& nameWithTakeover) {
|
||||
// if somebody activates on this block and they are the new best, then everybody activates on this block
|
||||
CClaimValue candidateValue;
|
||||
auto hasCandidate = getInfoForName(nameWithTakeover, candidateValue, 1);
|
||||
// now that they're all in get the winner:
|
||||
uint160 existingID;
|
||||
int existingHeight = 0;
|
||||
auto hasCurrentWinner = getLastTakeoverForName(nameWithTakeover, existingID, existingHeight);
|
||||
// we have a takeover if we had a winner and its changing or we never had a winner
|
||||
auto takeoverHappening = !hasCandidate || !hasCurrentWinner || existingID != candidateValue.claimId;
|
||||
|
||||
if (takeoverHappening && activateAllFor(nameWithTakeover))
|
||||
hasCandidate = getInfoForName(nameWithTakeover, candidateValue, 1);
|
||||
|
||||
// This is a super ugly hack to work around bug in old code.
|
||||
// The bug: un/support a name then update it. This will cause its takeover height to be reset to current.
|
||||
// This is because the old code with add to the cache without setting block originals when dealing in supports.
|
||||
if (nNextHeight < 658300) {
|
||||
auto wit = takeoverWorkarounds.find(std::make_pair(nNextHeight, nameWithTakeover));
|
||||
takeoverHappening |= wit != takeoverWorkarounds.end();
|
||||
}
|
||||
|
||||
logPrint << "Takeover on " << nameWithTakeover << " at " << nNextHeight << ", happening: " << takeoverHappening << ", set before: " << hasCurrentWinner << Clog::endl;
|
||||
|
||||
if (takeoverHappening) {
|
||||
if (hasCandidate)
|
||||
insertTakeoverQuery << nameWithTakeover << nNextHeight << candidateValue.claimId;
|
||||
else
|
||||
insertTakeoverQuery << nameWithTakeover << nNextHeight << nullptr;
|
||||
insertTakeoverQuery++;
|
||||
}
|
||||
};
|
||||
|
||||
insertTakeoverQuery.used(true);
|
||||
|
||||
nNextHeight++;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::activateAllFor(const std::string& name)
|
||||
{
|
||||
// now that we know a takeover is happening, we bring everybody in:
|
||||
auto ret = false;
|
||||
// all to activate now:
|
||||
db << "UPDATE claim SET activationHeight = ?1 WHERE nodeName = ?2 AND activationHeight > ?1 AND expirationHeight > ?1" << nNextHeight << name;
|
||||
ret |= db.rows_modified() > 0;
|
||||
|
||||
// then do the same for supports:
|
||||
db << "UPDATE support SET activationHeight = ?1 WHERE nodeName = ?2 AND activationHeight > ?1 AND expirationHeight > ?1" << nNextHeight << name;
|
||||
ret |= db.rows_modified() > 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::decrementBlock()
|
||||
{
|
||||
ensureTransacting();
|
||||
|
||||
nNextHeight--;
|
||||
|
||||
db << "INSERT INTO node(name) SELECT nodeName FROM claim "
|
||||
"WHERE expirationHeight = ? ON CONFLICT(name) DO UPDATE SET hash = NULL"
|
||||
<< nNextHeight;
|
||||
|
||||
db << "UPDATE node SET hash = NULL WHERE name IN("
|
||||
"SELECT nodeName FROM support WHERE expirationHeight = ?1 OR activationHeight = ?1 "
|
||||
"UNION SELECT nodeName FROM claim WHERE activationHeight = ?1)"
|
||||
<< nNextHeight;
|
||||
|
||||
db << "UPDATE claim SET activationHeight = validHeight WHERE activationHeight = ?"
|
||||
<< nNextHeight;
|
||||
|
||||
db << "UPDATE support SET activationHeight = validHeight WHERE activationHeight = ?"
|
||||
<< nNextHeight;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::finalizeDecrement()
|
||||
{
|
||||
db << "UPDATE node SET hash = NULL WHERE name IN "
|
||||
"(SELECT nodeName FROM claim WHERE activationHeight = ?1 AND expirationHeight > ?1 "
|
||||
"UNION SELECT nodeName FROM support WHERE activationHeight = ?1 AND expirationHeight > ?1 "
|
||||
"UNION SELECT name FROM takeover WHERE height = ?1)" << nNextHeight;
|
||||
|
||||
db << "DELETE FROM takeover WHERE height >= ?" << nNextHeight;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int CClaimTrieCacheBase::getDelayForName(const std::string& name, const uint160& claimId) const
|
||||
{
|
||||
uint160 winningClaimId;
|
||||
int winningTakeoverHeight;
|
||||
auto hasCurrentWinner = getLastTakeoverForName(name, winningClaimId, winningTakeoverHeight);
|
||||
if (hasCurrentWinner && winningClaimId == claimId) {
|
||||
assert(winningTakeoverHeight <= nNextHeight);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// NOTE: old code had a bug in it where nodes with no claims but with children would get left in the cache after removal.
|
||||
// This would cause the getNumBlocksOfContinuousOwnership to return zero (causing incorrect takeover height calc).
|
||||
auto hit = removalWorkaround.find(name);
|
||||
if (hit != removalWorkaround.end()) {
|
||||
removalWorkaround.erase(hit);
|
||||
return 0;
|
||||
}
|
||||
return hasCurrentWinner ? std::min((nNextHeight - winningTakeoverHeight) / base->nProportionalDelayFactor, 4032) : 0;
|
||||
}
|
||||
|
||||
std::string CClaimTrieCacheBase::adjustNameForValidHeight(const std::string& name, int validHeight) const
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::getProofForName(const std::string& name, const uint160& finalClaim, CClaimTrieProof& proof)
|
||||
{
|
||||
// cache the parent nodes
|
||||
getMerkleHash();
|
||||
proof = CClaimTrieProof();
|
||||
for (auto&& row: db << proofClaimQuery_s << name) {
|
||||
CClaimValue claim;
|
||||
std::string key;
|
||||
int takeoverHeight;
|
||||
row >> key >> takeoverHeight;
|
||||
bool fNodeHasValue = getInfoForName(key, claim);
|
||||
uint256 valueHash;
|
||||
if (fNodeHasValue)
|
||||
valueHash = getValueHash(claim.outPoint, takeoverHeight);
|
||||
|
||||
const auto pos = key.size();
|
||||
std::vector<std::pair<unsigned char, uint256>> children;
|
||||
for (auto&& child : childHashQuery << key) {
|
||||
std::string childKey;
|
||||
uint256 hash;
|
||||
child >> childKey >> hash;
|
||||
if (name.find(childKey) == 0) {
|
||||
for (auto i = pos; i + 1 < childKey.size(); ++i) {
|
||||
children.emplace_back(childKey[i], uint256{});
|
||||
proof.nodes.emplace_back(children, fNodeHasValue, valueHash);
|
||||
children.clear();
|
||||
valueHash.SetNull();
|
||||
fNodeHasValue = false;
|
||||
}
|
||||
children.emplace_back(childKey.back(), uint256{});
|
||||
continue;
|
||||
}
|
||||
completeHash(hash, childKey, pos);
|
||||
children.emplace_back(childKey[pos], hash);
|
||||
}
|
||||
childHashQuery++;
|
||||
if (key == name) {
|
||||
proof.hasValue = fNodeHasValue && claim.claimId == finalClaim;
|
||||
if (proof.hasValue) {
|
||||
proof.outPoint = claim.outPoint;
|
||||
proof.nHeightOfLastTakeover = takeoverHeight;
|
||||
}
|
||||
valueHash.SetNull();
|
||||
}
|
||||
proof.nodes.emplace_back(std::move(children), fNodeHasValue, valueHash);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CClaimTrieCacheBase::findNameForClaim(std::vector<unsigned char> claim, CClaimValue& value, std::string& name) const
|
||||
{
|
||||
if (claim.size() > 20)
|
||||
return false;
|
||||
auto maximum = claim;
|
||||
maximum.insert(maximum.end(), 20 - claim.size(), std::numeric_limits<unsigned char>::max());
|
||||
auto query = db << "SELECT nodeName, claimID, txID, txN, amount, activationHeight, updateHeight "
|
||||
"FROM claim WHERE REVERSE(claimID) BETWEEN ?1 AND ?2 "
|
||||
"AND activationHeight < ?3 AND expirationHeight >= ?3 LIMIT 2"
|
||||
<< claim << maximum << nNextHeight;
|
||||
auto hit = false;
|
||||
for (auto&& row: query) {
|
||||
if (hit) return false;
|
||||
row >> name >> value.claimId >> value.outPoint.hash >> value.outPoint.n
|
||||
>> value.nAmount >> value.nValidAtHeight >> value.nHeight;
|
||||
hit = true;
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
void CClaimTrieCacheBase::getNamesInTrie(std::function<void(const std::string&)> callback) const
|
||||
{
|
||||
db << "SELECT DISTINCT nodeName FROM claim WHERE activationHeight < ?1 AND expirationHeight >= ?1"
|
||||
<< nNextHeight >> [&callback](const std::string& name) {
|
||||
callback(name);
|
||||
};
|
||||
}
|
||||
|
||||
std::vector<uint160> CClaimTrieCacheBase::getActivatedClaims(int height) {
|
||||
std::vector<uint160> ret;
|
||||
auto query = db << "SELECT DISTINCT claimID FROM claim WHERE activationHeight = ?1 AND updateHeight < ?1" << height;
|
||||
for (auto&& row: query) {
|
||||
ret.emplace_back();
|
||||
row >> ret.back();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
std::vector<uint160> CClaimTrieCacheBase::getClaimsWithActivatedSupports(int height) {
|
||||
std::vector<uint160> ret;
|
||||
auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE activationHeight = ?1 AND blockHeight < ?1" << height;
|
||||
for (auto&& row: query) {
|
||||
ret.emplace_back();
|
||||
row >> ret.back();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
std::vector<uint160> CClaimTrieCacheBase::getExpiredClaims(int height) {
|
||||
std::vector<uint160> ret;
|
||||
auto query = db << "SELECT DISTINCT claimID FROM claim WHERE expirationHeight = ?1 AND updateHeight < ?1" << height;
|
||||
for (auto&& row: query) {
|
||||
ret.emplace_back();
|
||||
row >> ret.back();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
std::vector<uint160> CClaimTrieCacheBase::getClaimsWithExpiredSupports(int height) {
|
||||
std::vector<uint160> ret;
|
||||
auto query = db << "SELECT DISTINCT supportedClaimID FROM support WHERE expirationHeight = ?1 AND blockHeight < ?1" << height;
|
||||
for (auto&& row: query) {
|
||||
ret.emplace_back();
|
||||
row >> ret.back();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
#ifndef CLAIMTRIE_TRIE_H
|
||||
#define CLAIMTRIE_TRIE_H
|
||||
|
||||
#include <data.h>
|
||||
#include <sqlite.h>
|
||||
#include <txoutpoint.h>
|
||||
#include <uints.h>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
|
||||
uint256 getValueHash(const COutPoint& outPoint, int nHeightOfLastTakeover);
|
||||
|
||||
class CClaimTrie
|
||||
{
|
||||
friend class CClaimTrieCacheBase;
|
||||
friend class ClaimTrieChainFixture;
|
||||
friend class CClaimTrieCacheHashFork;
|
||||
friend class CClaimTrieCacheExpirationFork;
|
||||
friend class CClaimTrieCacheNormalizationFork;
|
||||
|
||||
public:
|
||||
CClaimTrie() = delete;
|
||||
CClaimTrie(CClaimTrie&&) = delete;
|
||||
CClaimTrie(const CClaimTrie&) = delete;
|
||||
CClaimTrie(std::size_t cacheBytes, bool fWipe, int height = 0,
|
||||
const std::string& dataDir = ".",
|
||||
int nNormalizedNameForkHeight = 1,
|
||||
int nMinRemovalWorkaroundHeight = 1,
|
||||
int nMaxRemovalWorkaroundHeight = -1,
|
||||
int64_t nOriginalClaimExpirationTime = 1,
|
||||
int64_t nExtendedClaimExpirationTime = 1,
|
||||
int64_t nExtendedClaimExpirationForkHeight = 1,
|
||||
int64_t nAllClaimsInMerkleForkHeight = 1,
|
||||
int proportionalDelayFactor = 32);
|
||||
|
||||
CClaimTrie& operator=(CClaimTrie&&) = delete;
|
||||
CClaimTrie& operator=(const CClaimTrie&) = delete;
|
||||
|
||||
bool empty();
|
||||
bool SyncToDisk();
|
||||
|
||||
protected:
|
||||
int nNextHeight;
|
||||
std::size_t dbCacheBytes;
|
||||
const std::string dbFile;
|
||||
sqlite::database db;
|
||||
const int nProportionalDelayFactor;
|
||||
|
||||
const int nNormalizedNameForkHeight;
|
||||
const int nMinRemovalWorkaroundHeight, nMaxRemovalWorkaroundHeight;
|
||||
const int64_t nOriginalClaimExpirationTime;
|
||||
const int64_t nExtendedClaimExpirationTime;
|
||||
const int64_t nExtendedClaimExpirationForkHeight;
|
||||
const int64_t nAllClaimsInMerkleForkHeight;
|
||||
};
|
||||
|
||||
class CClaimTrieCacheBase
|
||||
{
|
||||
public:
|
||||
explicit CClaimTrieCacheBase(CClaimTrie* base);
|
||||
virtual ~CClaimTrieCacheBase();
|
||||
|
||||
bool flush();
|
||||
bool checkConsistency();
|
||||
uint256 getMerkleHash();
|
||||
bool validateDb(int height, const uint256& rootHash);
|
||||
|
||||
std::size_t getTotalNamesInTrie() const;
|
||||
std::size_t getTotalClaimsInTrie() const;
|
||||
int64_t getTotalValueOfClaimsInTrie(bool fControllingOnly) const;
|
||||
|
||||
bool haveClaim(const std::string& name, const COutPoint& outPoint) const;
|
||||
bool haveClaimInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const;
|
||||
|
||||
bool haveSupport(const std::string& name, const COutPoint& outPoint) const;
|
||||
bool haveSupportInQueue(const std::string& name, const COutPoint& outPoint, int& nValidAtHeight) const;
|
||||
|
||||
bool addClaim(const std::string& name, const COutPoint& outPoint, const uint160& claimId, int64_t nAmount,
|
||||
int nHeight, int nValidHeight = -1, int originalHeight = -1);
|
||||
|
||||
bool addSupport(const std::string& name, const COutPoint& outPoint, const uint160& supportedClaimId, int64_t nAmount,
|
||||
int nHeight, int nValidHeight = -1);
|
||||
|
||||
bool removeClaim(const uint160& claimId, const COutPoint& outPoint, std::string& nodeName,
|
||||
int& validHeight, int& originalHeight);
|
||||
bool removeSupport(const COutPoint& outPoint, std::string& nodeName, int& validHeight);
|
||||
|
||||
virtual bool incrementBlock();
|
||||
virtual bool decrementBlock();
|
||||
virtual bool finalizeDecrement();
|
||||
|
||||
virtual int expirationTime() const;
|
||||
|
||||
virtual bool getProofForName(const std::string& name, const uint160& claim, CClaimTrieProof& proof);
|
||||
virtual bool getInfoForName(const std::string& name, CClaimValue& claim, int heightOffset = 0) const;
|
||||
|
||||
virtual CClaimSupportToName getClaimsForName(const std::string& name) const;
|
||||
virtual std::string adjustNameForValidHeight(const std::string& name, int validHeight) const;
|
||||
|
||||
void getNamesInTrie(std::function<void(const std::string&)> callback) const;
|
||||
bool getLastTakeoverForName(const std::string& name, uint160& claimId, int& takeoverHeight) const;
|
||||
bool findNameForClaim(std::vector<unsigned char> claim, CClaimValue& value, std::string& name) const;
|
||||
|
||||
std::vector<uint160> getActivatedClaims(int height);
|
||||
std::vector<uint160> getClaimsWithActivatedSupports(int height);
|
||||
std::vector<uint160> getExpiredClaims(int height);
|
||||
std::vector<uint160> getClaimsWithExpiredSupports(int height);
|
||||
|
||||
protected:
|
||||
int nNextHeight; // Height of the block that is being worked on, which is
|
||||
CClaimTrie* base;
|
||||
mutable sqlite::database db;
|
||||
mutable std::unordered_set<std::string> removalWorkaround;
|
||||
|
||||
mutable sqlite::database_binder claimHashQuery, childHashQuery, claimHashQueryLimit;
|
||||
|
||||
virtual uint256 computeNodeHash(const std::string& name, int takeoverHeight);
|
||||
supportEntryType getSupportsForName(const std::string& name) const;
|
||||
|
||||
virtual int getDelayForName(const std::string& name, const uint160& claimId) const;
|
||||
|
||||
bool deleteNodeIfPossible(const std::string& name, std::string& parent, int64_t& claims);
|
||||
void ensureTreeStructureIsUpToDate();
|
||||
void ensureTransacting();
|
||||
|
||||
private:
|
||||
bool transacting;
|
||||
// for unit test
|
||||
friend struct ClaimTrieChainFixture;
|
||||
friend class CClaimTrieCacheTest;
|
||||
|
||||
bool activateAllFor(const std::string& name);
|
||||
};
|
||||
|
||||
#endif // CLAIMTRIE_TRIE_H
|
||||
Loaded 100 of 373 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user