mirror of
https://github.com/XRPLF/rippled.git
synced 2026-01-11 18:25:23 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2084d61efa | ||
|
|
57b9da62bd | ||
|
|
79c583e1f7 | ||
|
|
5743dc4537 | ||
|
|
d86b1f8b7d | ||
|
|
d57f88fc18 | ||
|
|
24cf8ab8c7 | ||
|
|
e56a85cb3b | ||
|
|
d1fdea9bc8 |
3
.github/ISSUE_TEMPLATE/config.yml
vendored
3
.github/ISSUE_TEMPLATE/config.yml
vendored
@@ -3,6 +3,9 @@ contact_links:
|
||||
- name: XRP Ledger Documentation
|
||||
url: https://xrpl.org/
|
||||
about: All things about XRPL
|
||||
- name: General question for the community
|
||||
url: https://forum.xpring.io/c/community/
|
||||
about: Please ask and answer questions here.
|
||||
- name: Security bug bounty program
|
||||
url: https://ripple.com/bug-bounty/
|
||||
about: Please report security-relevant bugs in our software here.
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -104,5 +104,3 @@ Builds/VisualStudio2015/*.sdf
|
||||
CMakeSettings.json
|
||||
compile_commands.json
|
||||
.clangd
|
||||
packages
|
||||
pkg_out
|
||||
|
||||
@@ -82,7 +82,6 @@ target_sources (xrpl_core PRIVATE
|
||||
src/ripple/protocol/impl/PublicKey.cpp
|
||||
src/ripple/protocol/impl/Quality.cpp
|
||||
src/ripple/protocol/impl/Rate2.cpp
|
||||
src/ripple/protocol/impl/Rules.cpp
|
||||
src/ripple/protocol/impl/SField.cpp
|
||||
src/ripple/protocol/impl/SOTemplate.cpp
|
||||
src/ripple/protocol/impl/STAccount.cpp
|
||||
@@ -156,9 +155,7 @@ install (
|
||||
src/ripple/basics/MathUtilities.h
|
||||
src/ripple/basics/safe_cast.h
|
||||
src/ripple/basics/Slice.h
|
||||
src/ripple/basics/spinlock.h
|
||||
src/ripple/basics/StringUtilities.h
|
||||
src/ripple/basics/ThreadSafetyAnalysis.h
|
||||
src/ripple/basics/ToString.h
|
||||
src/ripple/basics/UnorderedContainers.h
|
||||
src/ripple/basics/XRPAmount.h
|
||||
@@ -212,7 +209,6 @@ install (
|
||||
src/ripple/protocol/PublicKey.h
|
||||
src/ripple/protocol/Quality.h
|
||||
src/ripple/protocol/Rate.h
|
||||
src/ripple/protocol/Rules.h
|
||||
src/ripple/protocol/SField.h
|
||||
src/ripple/protocol/SOTemplate.h
|
||||
src/ripple/protocol/STAccount.h
|
||||
@@ -399,23 +395,29 @@ target_sources (rippled PRIVATE
|
||||
src/ripple/app/paths/Pathfinder.cpp
|
||||
src/ripple/app/paths/RippleCalc.cpp
|
||||
src/ripple/app/paths/RippleLineCache.cpp
|
||||
src/ripple/app/paths/TrustLine.cpp
|
||||
src/ripple/app/paths/RippleState.cpp
|
||||
src/ripple/app/paths/impl/BookStep.cpp
|
||||
src/ripple/app/paths/impl/DirectStep.cpp
|
||||
src/ripple/app/paths/impl/PaySteps.cpp
|
||||
src/ripple/app/paths/impl/XRPEndpointStep.cpp
|
||||
src/ripple/app/rdb/backend/detail/impl/Node.cpp
|
||||
src/ripple/app/rdb/backend/detail/impl/Shard.cpp
|
||||
src/ripple/app/rdb/backend/impl/PostgresDatabase.cpp
|
||||
src/ripple/app/rdb/backend/impl/SQLiteDatabase.cpp
|
||||
src/ripple/app/rdb/impl/Download.cpp
|
||||
src/ripple/app/rdb/impl/PeerFinder.cpp
|
||||
src/ripple/app/rdb/impl/RelationalDatabase.cpp
|
||||
src/ripple/app/rdb/impl/ShardArchive.cpp
|
||||
src/ripple/app/rdb/impl/State.cpp
|
||||
src/ripple/app/rdb/impl/UnitaryShard.cpp
|
||||
src/ripple/app/rdb/impl/Vacuum.cpp
|
||||
src/ripple/app/rdb/impl/Wallet.cpp
|
||||
src/ripple/app/rdb/backend/RelationalDBInterfacePostgres.cpp
|
||||
src/ripple/app/rdb/backend/RelationalDBInterfaceSqlite.cpp
|
||||
src/ripple/app/rdb/impl/RelationalDBInterface.cpp
|
||||
src/ripple/app/rdb/impl/RelationalDBInterface_global.cpp
|
||||
src/ripple/app/rdb/impl/RelationalDBInterface_nodes.cpp
|
||||
src/ripple/app/rdb/impl/RelationalDBInterface_postgres.cpp
|
||||
src/ripple/app/rdb/impl/RelationalDBInterface_shards.cpp
|
||||
src/ripple/app/sidechain/Federator.cpp
|
||||
src/ripple/app/sidechain/FederatorEvents.cpp
|
||||
src/ripple/app/sidechain/impl/ChainListener.cpp
|
||||
src/ripple/app/sidechain/impl/DoorKeeper.cpp
|
||||
src/ripple/app/sidechain/impl/InitialSync.cpp
|
||||
src/ripple/app/sidechain/impl/MainchainListener.cpp
|
||||
src/ripple/app/sidechain/impl/SidechainListener.cpp
|
||||
src/ripple/app/sidechain/impl/SignatureCollector.cpp
|
||||
src/ripple/app/sidechain/impl/SignerList.cpp
|
||||
src/ripple/app/sidechain/impl/TicketHolder.cpp
|
||||
src/ripple/app/sidechain/impl/WebsocketClient.cpp
|
||||
src/ripple/app/tx/impl/ApplyContext.cpp
|
||||
src/ripple/app/tx/impl/BookTip.cpp
|
||||
src/ripple/app/tx/impl/CancelCheck.cpp
|
||||
@@ -429,11 +431,6 @@ target_sources (rippled PRIVATE
|
||||
src/ripple/app/tx/impl/DepositPreauth.cpp
|
||||
src/ripple/app/tx/impl/Escrow.cpp
|
||||
src/ripple/app/tx/impl/InvariantCheck.cpp
|
||||
src/ripple/app/tx/impl/NFTokenAcceptOffer.cpp
|
||||
src/ripple/app/tx/impl/NFTokenBurn.cpp
|
||||
src/ripple/app/tx/impl/NFTokenCancelOffer.cpp
|
||||
src/ripple/app/tx/impl/NFTokenCreateOffer.cpp
|
||||
src/ripple/app/tx/impl/NFTokenMint.cpp
|
||||
src/ripple/app/tx/impl/OfferStream.cpp
|
||||
src/ripple/app/tx/impl/PayChan.cpp
|
||||
src/ripple/app/tx/impl/Payment.cpp
|
||||
@@ -446,7 +443,6 @@ target_sources (rippled PRIVATE
|
||||
src/ripple/app/tx/impl/Transactor.cpp
|
||||
src/ripple/app/tx/impl/apply.cpp
|
||||
src/ripple/app/tx/impl/applySteps.cpp
|
||||
src/ripple/app/tx/impl/details/NFTokenUtils.cpp
|
||||
#[===============================[
|
||||
main sources:
|
||||
subdir: basics (partial)
|
||||
@@ -591,6 +587,7 @@ target_sources (rippled PRIVATE
|
||||
src/ripple/rpc/handlers/DepositAuthorized.cpp
|
||||
src/ripple/rpc/handlers/DownloadShard.cpp
|
||||
src/ripple/rpc/handlers/Feature1.cpp
|
||||
src/ripple/rpc/handlers/FederatorInfo.cpp
|
||||
src/ripple/rpc/handlers/Fee1.cpp
|
||||
src/ripple/rpc/handlers/FetchInfo.cpp
|
||||
src/ripple/rpc/handlers/GatewayBalances.cpp
|
||||
@@ -608,7 +605,6 @@ target_sources (rippled PRIVATE
|
||||
src/ripple/rpc/handlers/LogLevel.cpp
|
||||
src/ripple/rpc/handlers/LogRotate.cpp
|
||||
src/ripple/rpc/handlers/Manifest.cpp
|
||||
src/ripple/rpc/handlers/NFTOffers.cpp
|
||||
src/ripple/rpc/handlers/NodeToShard.cpp
|
||||
src/ripple/rpc/handlers/NoRippleCheck.cpp
|
||||
src/ripple/rpc/handlers/OwnerInfo.cpp
|
||||
@@ -703,9 +699,6 @@ if (tests)
|
||||
src/test/app/LoadFeeTrack_test.cpp
|
||||
src/test/app/Manifest_test.cpp
|
||||
src/test/app/MultiSign_test.cpp
|
||||
src/test/app/NFToken_test.cpp
|
||||
src/test/app/NFTokenBurn_test.cpp
|
||||
src/test/app/NFTokenDir_test.cpp
|
||||
src/test/app/OfferStream_test.cpp
|
||||
src/test/app/Offer_test.cpp
|
||||
src/test/app/OversizeMeta_test.cpp
|
||||
@@ -752,7 +745,6 @@ if (tests)
|
||||
src/test/basics/contract_test.cpp
|
||||
src/test/basics/FeeUnits_test.cpp
|
||||
src/test/basics/hardened_hash_test.cpp
|
||||
src/test/basics/join_test.cpp
|
||||
src/test/basics/mulDiv_test.cpp
|
||||
src/test/basics/tagged_integer_test.cpp
|
||||
#[===============================[
|
||||
@@ -855,7 +847,6 @@ if (tests)
|
||||
src/test/jtx/impl/sig.cpp
|
||||
src/test/jtx/impl/tag.cpp
|
||||
src/test/jtx/impl/ticket.cpp
|
||||
src/test/jtx/impl/token.cpp
|
||||
src/test/jtx/impl/trust.cpp
|
||||
src/test/jtx/impl/txflags.cpp
|
||||
src/test/jtx/impl/utility.cpp
|
||||
@@ -912,7 +903,6 @@ if (tests)
|
||||
src/test/protocol/InnerObjectFormats_test.cpp
|
||||
src/test/protocol/Issue_test.cpp
|
||||
src/test/protocol/KnownFormatToGRPC_test.cpp
|
||||
src/test/protocol/Hooks_test.cpp
|
||||
src/test/protocol/PublicKey_test.cpp
|
||||
src/test/protocol/Quality_test.cpp
|
||||
src/test/protocol/STAccount_test.cpp
|
||||
@@ -1011,18 +1001,17 @@ if (is_ci)
|
||||
target_compile_definitions(rippled PRIVATE RIPPLED_RUNNING_IN_CI)
|
||||
endif ()
|
||||
|
||||
if(reporting)
|
||||
set_target_properties(rippled PROPERTIES OUTPUT_NAME rippled-reporting)
|
||||
get_target_property(BIN_NAME rippled OUTPUT_NAME)
|
||||
message(STATUS "Reporting mode build: rippled renamed ${BIN_NAME}")
|
||||
target_compile_definitions(rippled PRIVATE RIPPLED_REPORTING)
|
||||
endif()
|
||||
if (reporting)
|
||||
target_compile_definitions(rippled PRIVATE RIPPLED_REPORTING)
|
||||
endif ()
|
||||
|
||||
# any files that don't play well with unity should be added here
|
||||
if (tests)
|
||||
set_source_files_properties(
|
||||
# these two seem to produce conflicts in beast teardown template methods
|
||||
src/test/rpc/ValidatorRPC_test.cpp
|
||||
src/test/rpc/ShardArchiveHandler_test.cpp
|
||||
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE)
|
||||
endif () #tests
|
||||
if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.16)
|
||||
# any files that don't play well with unity should be added here
|
||||
if (tests)
|
||||
set_source_files_properties(
|
||||
# these two seem to produce conflicts in beast teardown template methods
|
||||
src/test/rpc/ValidatorRPC_test.cpp
|
||||
src/test/rpc/ShardArchiveHandler_test.cpp
|
||||
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE)
|
||||
endif () #tests
|
||||
endif ()
|
||||
|
||||
@@ -31,7 +31,7 @@ if (tests)
|
||||
# find_path sets a CACHE variable, so don't try using a "local" variable.
|
||||
find_path (${variable} "${name}" ${ARGN})
|
||||
if (NOT ${variable})
|
||||
message (NOTICE "could not find ${name}")
|
||||
message (WARNING "could not find ${name}")
|
||||
else ()
|
||||
message (STATUS "found ${name}: ${${variable}}/${name}")
|
||||
endif ()
|
||||
|
||||
@@ -48,15 +48,12 @@ if (is_root_project)
|
||||
Builds/containers/centos-builder/Dockerfile
|
||||
Builds/containers/centos-builder/centos_setup.sh
|
||||
Builds/containers/centos-builder/extras.sh
|
||||
Builds/containers/shared/update-rippled.sh
|
||||
Builds/containers/shared/update_sources.sh
|
||||
Builds/containers/shared/rippled.service
|
||||
Builds/containers/shared/rippled-reporting.service
|
||||
Builds/containers/shared/build_deps.sh
|
||||
Builds/containers/shared/rippled.service
|
||||
Builds/containers/shared/update_sources.sh
|
||||
Builds/containers/shared/update-rippled.sh
|
||||
Builds/containers/packaging/rpm/rippled.spec
|
||||
Builds/containers/packaging/rpm/build_rpm.sh
|
||||
Builds/containers/packaging/rpm/50-rippled.preset
|
||||
Builds/containers/packaging/rpm/50-rippled-reporting.preset
|
||||
bin/getRippledInfo
|
||||
)
|
||||
exclude_from_default (rpm_container)
|
||||
@@ -89,7 +86,7 @@ if (is_root_project)
|
||||
add_custom_target (dpkg_container
|
||||
docker build
|
||||
--pull
|
||||
--build-arg DIST_TAG=18.04
|
||||
--build-arg DIST_TAG=16.04
|
||||
--build-arg GIT_COMMIT=${commit_hash}
|
||||
-t rippled-dpkg-builder:${container_label}
|
||||
$<$<BOOL:${dpkg_cache_from}>:--cache-from=${dpkg_cache_from}>
|
||||
@@ -99,40 +96,28 @@ if (is_root_project)
|
||||
USES_TERMINAL
|
||||
COMMAND_EXPAND_LISTS
|
||||
SOURCES
|
||||
Builds/containers/packaging/dpkg/debian/rippled-reporting.links
|
||||
Builds/containers/packaging/dpkg/debian/copyright
|
||||
Builds/containers/packaging/dpkg/debian/rules
|
||||
Builds/containers/packaging/dpkg/debian/rippled-reporting.install
|
||||
Builds/containers/packaging/dpkg/debian/rippled-reporting.postinst
|
||||
Builds/containers/packaging/dpkg/debian/rippled.links
|
||||
Builds/containers/packaging/dpkg/debian/rippled.prerm
|
||||
Builds/containers/packaging/dpkg/debian/rippled.postinst
|
||||
Builds/containers/packaging/dpkg/debian/rippled-dev.install
|
||||
Builds/containers/packaging/dpkg/debian/dirs
|
||||
Builds/containers/packaging/dpkg/debian/rippled.postrm
|
||||
Builds/containers/packaging/dpkg/debian/rippled.conffiles
|
||||
Builds/containers/packaging/dpkg/debian/compat
|
||||
Builds/containers/packaging/dpkg/debian/source/format
|
||||
Builds/containers/packaging/dpkg/debian/source/local-options
|
||||
Builds/containers/packaging/dpkg/debian/README.Debian
|
||||
Builds/containers/packaging/dpkg/debian/rippled.install
|
||||
Builds/containers/packaging/dpkg/debian/rippled.preinst
|
||||
Builds/containers/packaging/dpkg/debian/docs
|
||||
Builds/containers/packaging/dpkg/debian/control
|
||||
Builds/containers/packaging/dpkg/debian/rippled-reporting.dirs
|
||||
Builds/containers/packaging/dpkg/build_dpkg.sh
|
||||
Builds/containers/ubuntu-builder/Dockerfile
|
||||
Builds/containers/ubuntu-builder/ubuntu_setup.sh
|
||||
bin/getRippledInfo
|
||||
Builds/containers/shared/install_cmake.sh
|
||||
Builds/containers/shared/install_boost.sh
|
||||
Builds/containers/shared/update-rippled.sh
|
||||
Builds/containers/shared/update_sources.sh
|
||||
Builds/containers/shared/build_deps.sh
|
||||
Builds/containers/shared/rippled.service
|
||||
Builds/containers/shared/rippled-reporting.service
|
||||
Builds/containers/shared/rippled-logrotate
|
||||
Builds/containers/shared/update-rippled-cron
|
||||
Builds/containers/shared/update_sources.sh
|
||||
Builds/containers/shared/update-rippled.sh
|
||||
Builds/containers/packaging/dpkg/build_dpkg.sh
|
||||
Builds/containers/packaging/dpkg/debian/README.Debian
|
||||
Builds/containers/packaging/dpkg/debian/conffiles
|
||||
Builds/containers/packaging/dpkg/debian/control
|
||||
Builds/containers/packaging/dpkg/debian/copyright
|
||||
Builds/containers/packaging/dpkg/debian/dirs
|
||||
Builds/containers/packaging/dpkg/debian/docs
|
||||
Builds/containers/packaging/dpkg/debian/rippled-dev.install
|
||||
Builds/containers/packaging/dpkg/debian/rippled.install
|
||||
Builds/containers/packaging/dpkg/debian/rippled.links
|
||||
Builds/containers/packaging/dpkg/debian/rippled.postinst
|
||||
Builds/containers/packaging/dpkg/debian/rippled.postrm
|
||||
Builds/containers/packaging/dpkg/debian/rippled.preinst
|
||||
Builds/containers/packaging/dpkg/debian/rippled.prerm
|
||||
Builds/containers/packaging/dpkg/debian/rules
|
||||
bin/getRippledInfo
|
||||
)
|
||||
exclude_from_default (dpkg_container)
|
||||
add_custom_target (dpkg
|
||||
@@ -202,3 +187,4 @@ if (is_root_project)
|
||||
message (STATUS "docker NOT found -- won't be able to build containers for packaging")
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
|
||||
@@ -72,8 +72,10 @@ if ("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}")
|
||||
"directory from ${CMAKE_CURRENT_SOURCE_DIR} and try building in a separate directory.")
|
||||
endif ()
|
||||
|
||||
if (MSVC AND CMAKE_GENERATOR_PLATFORM STREQUAL "Win32")
|
||||
message (FATAL_ERROR "Visual Studio 32-bit build is not supported.")
|
||||
if ("${CMAKE_GENERATOR}" MATCHES "Visual Studio" AND
|
||||
NOT ("${CMAKE_GENERATOR}" MATCHES .*Win64.*))
|
||||
message (FATAL_ERROR
|
||||
"Visual Studio 32-bit build is not supported. Use -G\"${CMAKE_GENERATOR} Win64\"")
|
||||
endif ()
|
||||
|
||||
if (NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||
|
||||
@@ -10,8 +10,13 @@ option (tests "Build tests" ON)
|
||||
|
||||
option (unity "Creates a build using UNITY support in cmake. This is the default" ON)
|
||||
if (unity)
|
||||
if (NOT is_ci)
|
||||
set (CMAKE_UNITY_BUILD_BATCH_SIZE 15 CACHE STRING "")
|
||||
if (CMAKE_VERSION VERSION_LESS 3.16)
|
||||
message (WARNING "unity option only supported for with cmake 3.16+ (please upgrade)")
|
||||
set (unity OFF CACHE BOOL "unity only available for cmake 3.16+" FORCE)
|
||||
else ()
|
||||
if (NOT is_ci)
|
||||
set (CMAKE_UNITY_BUILD_BATCH_SIZE 15 CACHE STRING "")
|
||||
endif ()
|
||||
endif ()
|
||||
endif ()
|
||||
if (is_gcc OR is_clang)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
option (validator_keys "Enables building of validator-keys-tool as a separate target (imported via FetchContent)" OFF)
|
||||
|
||||
if (validator_keys)
|
||||
if (validator_keys AND CMAKE_VERSION VERSION_GREATER_EQUAL 3.11)
|
||||
git_branch (current_branch)
|
||||
# default to tracking VK develop branch unless we are on master/release
|
||||
if (NOT (current_branch STREQUAL "master" OR current_branch STREQUAL "release"))
|
||||
@@ -20,3 +20,5 @@ if (validator_keys)
|
||||
endif ()
|
||||
add_subdirectory (${validator_keys_src_SOURCE_DIR} ${CMAKE_BINARY_DIR}/validator-keys)
|
||||
endif ()
|
||||
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ if (local_libarchive)
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--target archive_static
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -43,7 +43,7 @@ else()
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--target lz4_static
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -8,19 +8,35 @@
|
||||
|
||||
if (is_root_project) # NuDB not needed in the case of xrpl_core inclusion build
|
||||
add_library (nudb INTERFACE)
|
||||
FetchContent_Declare(
|
||||
nudb_src
|
||||
GIT_REPOSITORY https://github.com/CPPAlliance/NuDB.git
|
||||
GIT_TAG 2.0.5
|
||||
)
|
||||
FetchContent_GetProperties(nudb_src)
|
||||
if(NOT nudb_src_POPULATED)
|
||||
message (STATUS "Pausing to download NuDB...")
|
||||
FetchContent_Populate(nudb_src)
|
||||
endif()
|
||||
if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.11)
|
||||
FetchContent_Declare(
|
||||
nudb_src
|
||||
GIT_REPOSITORY https://github.com/CPPAlliance/NuDB.git
|
||||
GIT_TAG 2.0.5
|
||||
)
|
||||
FetchContent_GetProperties(nudb_src)
|
||||
if(NOT nudb_src_POPULATED)
|
||||
message (STATUS "Pausing to download NuDB...")
|
||||
FetchContent_Populate(nudb_src)
|
||||
endif()
|
||||
else ()
|
||||
ExternalProject_Add (nudb_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/CPPAlliance/NuDB.git
|
||||
GIT_TAG 2.0.5
|
||||
CONFIGURE_COMMAND ""
|
||||
BUILD_COMMAND ""
|
||||
TEST_COMMAND ""
|
||||
INSTALL_COMMAND ""
|
||||
)
|
||||
ExternalProject_Get_Property (nudb_src SOURCE_DIR)
|
||||
set (nudb_src_SOURCE_DIR "${SOURCE_DIR}")
|
||||
file (MAKE_DIRECTORY ${nudb_src_SOURCE_DIR}/include)
|
||||
add_dependencies (nudb nudb_src)
|
||||
endif ()
|
||||
|
||||
file(TO_CMAKE_PATH "${nudb_src_SOURCE_DIR}" nudb_src_SOURCE_DIR)
|
||||
# specify as system includes so as to avoid warnings
|
||||
# specify as system includes so as to avoid warnings
|
||||
target_include_directories (nudb SYSTEM INTERFACE ${nudb_src_SOURCE_DIR}/include)
|
||||
target_link_libraries (nudb
|
||||
INTERFACE
|
||||
|
||||
@@ -13,7 +13,7 @@ if(reporting)
|
||||
ExternalProject_Add(postgres_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/postgres/postgres.git
|
||||
GIT_TAG REL_14_5
|
||||
GIT_TAG master
|
||||
CONFIGURE_COMMAND ./configure --without-readline > /dev/null
|
||||
BUILD_COMMAND ${CMAKE_COMMAND} -E env --unset=MAKELEVEL make
|
||||
UPDATE_COMMAND ""
|
||||
|
||||
@@ -65,7 +65,7 @@ if (local_protobuf OR NOT (Protobuf_FOUND AND Protobuf_PROTOC_EXECUTABLE AND pro
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
TEST_COMMAND ""
|
||||
INSTALL_COMMAND
|
||||
${CMAKE_COMMAND} -E env --unset=DESTDIR ${CMAKE_COMMAND} --build . --config $<CONFIG> --target install
|
||||
|
||||
@@ -136,7 +136,7 @@ if (local_rocksdb)
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -42,7 +42,7 @@ else()
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -113,7 +113,7 @@ else()
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -56,7 +56,7 @@ else()
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -11,7 +11,7 @@ if(reporting)
|
||||
ExternalProject_Add(zlib_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/madler/zlib.git
|
||||
GIT_TAG v1.2.12
|
||||
GIT_TAG master
|
||||
INSTALL_COMMAND ""
|
||||
BUILD_BYPRODUCTS <BINARY_DIR>/${ep_lib_prefix}z.a
|
||||
LOG_BUILD TRUE
|
||||
@@ -45,7 +45,7 @@ if(reporting)
|
||||
ExternalProject_Add(krb5_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/krb5/krb5.git
|
||||
GIT_TAG krb5-1.20-final
|
||||
GIT_TAG master
|
||||
UPDATE_COMMAND ""
|
||||
CONFIGURE_COMMAND autoreconf src && CFLAGS=-fcommon ./src/configure --enable-static --disable-shared > /dev/null
|
||||
BUILD_IN_SOURCE 1
|
||||
@@ -80,7 +80,7 @@ if(reporting)
|
||||
ExternalProject_Add(libuv_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/libuv/libuv.git
|
||||
GIT_TAG v1.44.2
|
||||
GIT_TAG v1.x
|
||||
INSTALL_COMMAND ""
|
||||
BUILD_BYPRODUCTS <BINARY_DIR>/${ep_lib_prefix}uv_a.a
|
||||
LOG_BUILD TRUE
|
||||
@@ -106,14 +106,12 @@ if(reporting)
|
||||
ExternalProject_Add(cassandra_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/datastax/cpp-driver.git
|
||||
GIT_TAG 2.16.2
|
||||
GIT_TAG master
|
||||
CMAKE_ARGS
|
||||
-DLIBUV_ROOT_DIR=${BINARY_DIR}
|
||||
-DLIBUV_LIBARY=${BINARY_DIR}/libuv_a.a
|
||||
-DLIBUV_INCLUDE_DIR=${SOURCE_DIR}/include
|
||||
-DCASS_BUILD_STATIC=ON
|
||||
-DCASS_BUILD_SHARED=OFF
|
||||
-DOPENSSL_ROOT_DIR=/opt/local/openssl
|
||||
INSTALL_COMMAND ""
|
||||
BUILD_BYPRODUCTS <BINARY_DIR>/${ep_lib_prefix}cassandra_static.a
|
||||
LOG_BUILD TRUE
|
||||
|
||||
@@ -9,10 +9,41 @@
|
||||
|
||||
find_package (date QUIET)
|
||||
if (NOT TARGET date::date)
|
||||
FetchContent_Declare(
|
||||
hh_date_src
|
||||
GIT_REPOSITORY https://github.com/HowardHinnant/date.git
|
||||
GIT_TAG fc4cf092f9674f2670fb9177edcdee870399b829
|
||||
)
|
||||
FetchContent_MakeAvailable(hh_date_src)
|
||||
if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.14)
|
||||
FetchContent_Declare(
|
||||
hh_date_src
|
||||
GIT_REPOSITORY https://github.com/HowardHinnant/date.git
|
||||
GIT_TAG fc4cf092f9674f2670fb9177edcdee870399b829
|
||||
)
|
||||
FetchContent_MakeAvailable(hh_date_src)
|
||||
else ()
|
||||
ExternalProject_Add (hh_date_src
|
||||
PREFIX ${nih_cache_path}
|
||||
GIT_REPOSITORY https://github.com/HowardHinnant/date.git
|
||||
GIT_TAG fc4cf092f9674f2670fb9177edcdee870399b829
|
||||
CONFIGURE_COMMAND ""
|
||||
BUILD_COMMAND ""
|
||||
TEST_COMMAND ""
|
||||
INSTALL_COMMAND ""
|
||||
)
|
||||
ExternalProject_Get_Property (hh_date_src SOURCE_DIR)
|
||||
set (hh_date_src_SOURCE_DIR "${SOURCE_DIR}")
|
||||
file (MAKE_DIRECTORY ${hh_date_src_SOURCE_DIR}/include)
|
||||
add_library (date_interface INTERFACE)
|
||||
add_library (date::date ALIAS date_interface)
|
||||
add_dependencies (date_interface hh_date_src)
|
||||
file (TO_CMAKE_PATH "${hh_date_src_SOURCE_DIR}" hh_date_src_SOURCE_DIR)
|
||||
target_include_directories (date_interface
|
||||
SYSTEM INTERFACE
|
||||
$<BUILD_INTERFACE:${hh_date_src_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>)
|
||||
install (
|
||||
FILES
|
||||
${hh_date_src_SOURCE_DIR}/include/date/date.h
|
||||
DESTINATION include/date)
|
||||
install (TARGETS date_interface
|
||||
EXPORT RippleExports
|
||||
INCLUDES DESTINATION include)
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
|
||||
@@ -112,7 +112,7 @@ else ()
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
TEST_COMMAND ""
|
||||
INSTALL_COMMAND
|
||||
${CMAKE_COMMAND} -E env --unset=DESTDIR ${CMAKE_COMMAND} --build . --config $<CONFIG> --target install
|
||||
@@ -169,7 +169,7 @@ else ()
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
TEST_COMMAND ""
|
||||
INSTALL_COMMAND
|
||||
${CMAKE_COMMAND} -E env --unset=DESTDIR ${CMAKE_COMMAND} --build . --config $<CONFIG> --target install
|
||||
@@ -237,7 +237,7 @@ else ()
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $<CONFIG>
|
||||
--parallel ${ep_procs}
|
||||
$<$<VERSION_GREATER_EQUAL:${CMAKE_VERSION},3.12>:--parallel ${ep_procs}>
|
||||
$<$<BOOL:${is_multiconfig}>:
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E copy
|
||||
|
||||
@@ -22,7 +22,6 @@ time cmake \
|
||||
-Dpackages_only=ON \
|
||||
-Dcontainer_label="${container_tag}" \
|
||||
-Dhave_package_container=ON \
|
||||
-DCMAKE_VERBOSE_MAKEFILE=ON \
|
||||
-Dunity=OFF \
|
||||
-DCMAKE_VERBOSE_MAKEFILE=OFF \
|
||||
-G Ninja ../..
|
||||
time cmake --build . --target ${pkgtype} -- -v
|
||||
time cmake --build . --target ${pkgtype}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env sh
|
||||
set -e
|
||||
set -ex
|
||||
# used as a before/setup script for docker steps in gitlab-ci
|
||||
# expects to be run in standard alpine/dind image
|
||||
echo $(nproc)
|
||||
@@ -13,3 +13,4 @@ apk add \
|
||||
pip3 install awscli
|
||||
# list curdir contents to build log:
|
||||
ls -la
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env sh
|
||||
set -e
|
||||
set -ex
|
||||
action=$1
|
||||
filter=$2
|
||||
|
||||
@@ -15,9 +15,7 @@ cd build/dpkg/packages
|
||||
CURLARGS="-sk -X${action} -urippled:${ARTIFACTORY_DEPLOY_KEY_RIPPLED}"
|
||||
RIPPLED_PKG=$(ls rippled_*.deb)
|
||||
RIPPLED_DEV_PKG=$(ls rippled-dev_*.deb)
|
||||
RIPPLED_REPORTING_PKG=$(ls rippled-reporting_*.deb)
|
||||
RIPPLED_DBG_PKG=$(ls rippled-dbgsym_*.deb)
|
||||
RIPPLED_REPORTING_DBG_PKG=$(ls rippled-reporting-dbgsym_*.deb)
|
||||
# TODO - where to upload src tgz?
|
||||
RIPPLED_SRC=$(ls rippled_*.orig.tar.gz)
|
||||
DEB_MATRIX=";deb.component=${COMPONENT};deb.architecture=amd64"
|
||||
@@ -25,7 +23,7 @@ for dist in stretch buster bullseye bionic focal jammy; do
|
||||
DEB_MATRIX="${DEB_MATRIX};deb.distribution=${dist}"
|
||||
done
|
||||
echo "{ \"debs\": {" > "${TOPDIR}/files.info"
|
||||
for deb in ${RIPPLED_PKG} ${RIPPLED_DEV_PKG} ${RIPPLED_DBG_PKG} ${RIPPLED_REPORTING_PKG} ${RIPPLED_REPORTING_DBG_PKG}; do
|
||||
for deb in ${RIPPLED_PKG} ${RIPPLED_DEV_PKG} ${RIPPLED_DBG_PKG} ; do
|
||||
# first item doesn't get a comma separator
|
||||
if [ $deb != $RIPPLED_PKG ] ; then
|
||||
echo "," >> "${TOPDIR}/files.info"
|
||||
@@ -50,11 +48,10 @@ cd build/rpm/packages
|
||||
RIPPLED_PKG=$(ls rippled-[0-9]*.x86_64.rpm)
|
||||
RIPPLED_DEV_PKG=$(ls rippled-devel*.rpm)
|
||||
RIPPLED_DBG_PKG=$(ls rippled-debuginfo*.rpm)
|
||||
RIPPLED_REPORTING_PKG=$(ls rippled-reporting*.rpm)
|
||||
# TODO - where to upload src rpm ?
|
||||
RIPPLED_SRC=$(ls rippled-[0-9]*.src.rpm)
|
||||
echo "\"rpms\": {" >> "${TOPDIR}/files.info"
|
||||
for rpm in ${RIPPLED_PKG} ${RIPPLED_DEV_PKG} ${RIPPLED_DBG_PKG} ${RIPPLED_REPORTING_PKG}; do
|
||||
for rpm in ${RIPPLED_PKG} ${RIPPLED_DEV_PKG} ${RIPPLED_DBG_PKG} ; do
|
||||
# first item doesn't get a comma separator
|
||||
if [ $rpm != $RIPPLED_PKG ] ; then
|
||||
echo "," >> "${TOPDIR}/files.info"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env sh
|
||||
set -e
|
||||
set -ex
|
||||
install_from=$1
|
||||
use_private=${2:-0} # this option not currently needed by any CI scripts,
|
||||
# reserved for possible future use
|
||||
@@ -61,11 +61,7 @@ if [ "${pkgtype}" = "dpkg" ] ; then
|
||||
else
|
||||
yum -y update
|
||||
if [ "${install_from}" = "repo" ] ; then
|
||||
pkgs=("yum-utils coreutils util-linux")
|
||||
if [ "$ID" = "rocky" ]; then
|
||||
pkgs="${pkgs[@]/coreutils}"
|
||||
fi
|
||||
yum install -y $pkgs
|
||||
yum -y install yum-utils coreutils util-linux
|
||||
REPOFILE="/etc/yum.repos.d/artifactory.repo"
|
||||
echo "[Artifactory]" > ${REPOFILE}
|
||||
echo "name=Artifactory" >> ${REPOFILE}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env sh
|
||||
set -e
|
||||
set -ex
|
||||
docker login -u rippled \
|
||||
-p ${ARTIFACTORY_DEPLOY_KEY_RIPPLED} "${ARTIFACTORY_HUB}"
|
||||
# this gives us rippled_version :
|
||||
@@ -19,3 +19,4 @@ for label in ${rippled_version} latest ; do
|
||||
docker push \
|
||||
"${ARTIFACTORY_HUB}/${DPKG_CONTAINER_NAME}:${label}_${CI_COMMIT_REF_SLUG}"
|
||||
done
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ set -ex
|
||||
# make sure pkg source files are up to date with repo
|
||||
cd /opt/rippled_bld/pkg
|
||||
cp -fpru rippled/Builds/containers/packaging/dpkg/debian/. debian/
|
||||
cp -fpu rippled/Builds/containers/shared/rippled*.service debian/
|
||||
cp -fpu rippled/Builds/containers/shared/rippled.service debian/
|
||||
cp -fpu rippled/Builds/containers/shared/update_sources.sh .
|
||||
source update_sources.sh
|
||||
|
||||
@@ -52,15 +52,14 @@ rc=$?; if [[ $rc != 0 ]]; then
|
||||
error "error building dpkg"
|
||||
fi
|
||||
cd ..
|
||||
ls -latr
|
||||
|
||||
# copy artifacts
|
||||
cp rippled-dev_${RIPPLED_DPKG_FULL_VERSION}_amd64.deb ${PKG_OUTDIR}
|
||||
cp rippled-reporting_${RIPPLED_DPKG_FULL_VERSION}_amd64.deb ${PKG_OUTDIR}
|
||||
cp rippled_${RIPPLED_DPKG_FULL_VERSION}_amd64.deb ${PKG_OUTDIR}
|
||||
cp rippled_${RIPPLED_DPKG_FULL_VERSION}.dsc ${PKG_OUTDIR}
|
||||
# dbgsym suffix is ddeb under newer debuild, but just deb under earlier
|
||||
cp rippled-dbgsym_${RIPPLED_DPKG_FULL_VERSION}_amd64.* ${PKG_OUTDIR}
|
||||
cp rippled-reporting-dbgsym_${RIPPLED_DPKG_FULL_VERSION}_amd64.* ${PKG_OUTDIR}
|
||||
cp rippled_${RIPPLED_DPKG_FULL_VERSION}_amd64.changes ${PKG_OUTDIR}
|
||||
cp rippled_${RIPPLED_DPKG_FULL_VERSION}_amd64.build ${PKG_OUTDIR}
|
||||
cp rippled_${RIPPLED_DPKG_VERSION}.orig.tar.gz ${PKG_OUTDIR}
|
||||
@@ -82,20 +81,15 @@ DEB_SHA256=$(cat shasums | \
|
||||
grep "rippled_${RIPPLED_DPKG_VERSION}-1_amd64.deb" | cut -d " " -f 1)
|
||||
DBG_SHA256=$(cat shasums | \
|
||||
grep "rippled-dbgsym_${RIPPLED_DPKG_VERSION}-1_amd64.*" | cut -d " " -f 1)
|
||||
REPORTING_DBG_SHA256=$(cat shasums | \
|
||||
grep "rippled-reporting-dbgsym_${RIPPLED_DPKG_VERSION}-1_amd64.*" | cut -d " " -f 1)
|
||||
DEV_SHA256=$(cat shasums | \
|
||||
grep "rippled-dev_${RIPPLED_DPKG_VERSION}-1_amd64.deb" | cut -d " " -f 1)
|
||||
REPORTING_SHA256=$(cat shasums | \
|
||||
grep "rippled-reporting_${RIPPLED_DPKG_VERSION}-1_amd64.deb" | cut -d " " -f 1)
|
||||
SRC_SHA256=$(cat shasums | \
|
||||
grep "rippled_${RIPPLED_DPKG_VERSION}.orig.tar.gz" | cut -d " " -f 1)
|
||||
echo "deb_sha256=${DEB_SHA256}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dbg_sha256=${DBG_SHA256}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dev_sha256=${DEV_SHA256}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "reporting_sha256=${REPORTING_SHA256}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "reporting_dbg_sha256=${REPORTING_DBG_SHA256}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "src_sha256=${SRC_SHA256}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "rippled_version=${RIPPLED_VERSION}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dpkg_version=${RIPPLED_DPKG_VERSION}" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dpkg_full_version=${RIPPLED_DPKG_FULL_VERSION}" >> ${PKG_OUTDIR}/build_vars
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
10
|
||||
9
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
/opt/ripple/etc/rippled.cfg
|
||||
/opt/ripple/etc/validators.txt
|
||||
/etc/logrotate.d/rippled
|
||||
@@ -12,12 +12,6 @@ Multi-Arch: foreign
|
||||
Depends: ${misc:Depends}, ${shlibs:Depends}
|
||||
Description: rippled daemon
|
||||
|
||||
Package: rippled-reporting
|
||||
Architecture: any
|
||||
Multi-Arch: foreign
|
||||
Depends: ${misc:Depends}, ${shlibs:Depends}
|
||||
Description: rippled reporting daemon
|
||||
|
||||
Package: rippled-dev
|
||||
Section: devel
|
||||
Recommends: rippled (= ${binary:Version})
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
/var/log/rippled-reporting/
|
||||
/var/lib/rippled-reporting/
|
||||
/etc/systemd/system/rippled-reporting.service.d/
|
||||
@@ -1,8 +0,0 @@
|
||||
bld/rippled-reporting/rippled-reporting opt/rippled-reporting/bin
|
||||
cfg/rippled-reporting.cfg opt/rippled-reporting/etc
|
||||
debian/tmp/opt/rippled-reporting/etc/validators.txt opt/rippled-reporting/etc
|
||||
|
||||
opt/rippled-reporting/bin/update-rippled-reporting.sh
|
||||
opt/rippled-reporting/bin/getRippledReportingInfo
|
||||
opt/rippled-reporting/etc/update-rippled-reporting-cron
|
||||
etc/logrotate.d/rippled-reporting
|
||||
@@ -1,3 +0,0 @@
|
||||
opt/rippled-reporting/etc/rippled-reporting.cfg etc/opt/rippled-reporting/rippled-reporting.cfg
|
||||
opt/rippled-reporting/etc/validators.txt etc/opt/rippled-reporting/validators.txt
|
||||
opt/rippled-reporting/bin/rippled-reporting usr/local/bin/rippled-reporting
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
USER_NAME=rippled-reporting
|
||||
GROUP_NAME=rippled-reporting
|
||||
case "$1" in
|
||||
configure)
|
||||
id -u $USER_NAME >/dev/null 2>&1 || \
|
||||
adduser --system --quiet \
|
||||
--home /nonexistent --no-create-home \
|
||||
--disabled-password \
|
||||
--group "$GROUP_NAME"
|
||||
chown -R $USER_NAME:$GROUP_NAME /var/log/rippled-reporting/
|
||||
chown -R $USER_NAME:$GROUP_NAME /var/lib/rippled-reporting/
|
||||
chmod 755 /var/log/rippled-reporting/
|
||||
chmod 755 /var/lib/rippled-reporting/
|
||||
chown -R $USER_NAME:$GROUP_NAME /opt/rippled-reporting
|
||||
|
||||
;;
|
||||
|
||||
abort-upgrade|abort-remove|abort-deconfigure)
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "postinst called with unknown argument \`$1'" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
|
||||
#DEBHELPER#
|
||||
|
||||
exit 0
|
||||
@@ -5,4 +5,4 @@ opt/ripple/bin/getRippledInfo
|
||||
opt/ripple/etc/rippled.cfg
|
||||
opt/ripple/etc/validators.txt
|
||||
opt/ripple/etc/update-rippled-cron
|
||||
etc/logrotate.d/rippled
|
||||
etc/logrotate.d/rippled
|
||||
|
||||
@@ -16,46 +16,28 @@ override_dh_systemd_start:
|
||||
|
||||
override_dh_auto_configure:
|
||||
env
|
||||
rm -rf bld && mkdir -p bld/rippled
|
||||
cd bld/rippled && \
|
||||
cmake ../.. -G Ninja \
|
||||
rm -rf bld
|
||||
mkdir -p bld
|
||||
cd bld && \
|
||||
cmake .. -G Ninja \
|
||||
-DCMAKE_INSTALL_PREFIX=/opt/ripple \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-Dstatic=ON \
|
||||
-Dunity=OFF \
|
||||
-Dvalidator_keys=ON \
|
||||
-Dunity=OFF \
|
||||
-DCMAKE_VERBOSE_MAKEFILE=OFF
|
||||
|
||||
|
||||
cmake -S . \
|
||||
-B bld/rippled-reporting \
|
||||
-G Ninja \
|
||||
-DCMAKE_INSTALL_PREFIX=/opt/rippled-reporting \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-Dstatic=ON \
|
||||
-Dunity=OFF \
|
||||
-DCMAKE_VERBOSE_MAKEFILE=OFF \
|
||||
-Dreporting=ON
|
||||
|
||||
override_dh_auto_build:
|
||||
cmake --build bld/rippled --target rippled --target validator-keys --parallel
|
||||
cmake --build bld/rippled-reporting --target rippled --parallel
|
||||
cd bld && \
|
||||
cmake --build . --target rippled --target validator-keys --parallel
|
||||
|
||||
override_dh_auto_install:
|
||||
cmake --install bld/rippled --prefix debian/tmp/opt/ripple
|
||||
install -D bld/rippled/validator-keys/validator-keys debian/tmp/opt/ripple/bin/validator-keys
|
||||
cd bld && DESTDIR=../debian/tmp cmake --build . --target install
|
||||
install -D bld/validator-keys/validator-keys debian/tmp/opt/ripple/bin/validator-keys
|
||||
install -D Builds/containers/shared/update-rippled.sh debian/tmp/opt/ripple/bin/update-rippled.sh
|
||||
install -D bin/getRippledInfo debian/tmp/opt/ripple/bin/getRippledInfo
|
||||
install -D Builds/containers/shared/update-rippled-cron debian/tmp/opt/ripple/etc/update-rippled-cron
|
||||
install -D Builds/containers/shared/rippled-logrotate debian/tmp/etc/logrotate.d/rippled
|
||||
rm -rf debian/tmp/opt/ripple/lib64/cmake/date
|
||||
|
||||
mkdir -p debian/tmp/opt/rippled-reporting/etc
|
||||
cp cfg/validators-example.txt debian/tmp/opt/rippled-reporting/etc/validators.txt
|
||||
install -D bld/rippled/validator-keys/validator-keys debian/tmp/opt/rippled-reporting/bin/validator-keys
|
||||
|
||||
sed -E 's/rippled?/rippled-reporting/g' Builds/containers/shared/update-rippled.sh > debian/tmp/opt/rippled-reporting/bin/update-rippled-reporting.sh
|
||||
sed -E 's/rippled?/rippled-reporting/g' bin/getRippledInfo > debian/tmp/opt/rippled-reporting/bin/getRippledReportingInfo
|
||||
sed -E 's/rippled?/rippled-reporting/g' Builds/containers/shared/update-rippled-cron > debian/tmp/opt/rippled-reporting/etc/update-rippled-reporting-cron
|
||||
sed -E 's/rippled?/rippled-reporting/g' Builds/containers/shared/rippled-logrotate > debian/tmp/etc/logrotate.d/rippled-reporting
|
||||
rm -rf bld
|
||||
rm -rf bld_vl
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
enable rippled-reporting.service
|
||||
@@ -30,8 +30,8 @@ fi
|
||||
|
||||
cd /opt/rippled_bld/pkg/rippled
|
||||
if [[ -n $(git status --porcelain) ]]; then
|
||||
git status
|
||||
error "Unstaged changes in this repo - please commit first"
|
||||
git status
|
||||
error "Unstaged changes in this repo - please commit first"
|
||||
fi
|
||||
git archive --format tar.gz --prefix rippled/ -o ../rpmbuild/SOURCES/rippled.tar.gz HEAD
|
||||
# TODO include validator-keys sources
|
||||
@@ -54,22 +54,18 @@ cp ./rpmbuild/SRPMS/* ${PKG_OUTDIR}
|
||||
RPM_MD5SUM=$(rpm -q --queryformat '%{SIGMD5}\n' -p ./rpmbuild/RPMS/x86_64/rippled-[0-9]*.rpm 2>/dev/null)
|
||||
DBG_MD5SUM=$(rpm -q --queryformat '%{SIGMD5}\n' -p ./rpmbuild/RPMS/x86_64/rippled-debuginfo*.rpm 2>/dev/null)
|
||||
DEV_MD5SUM=$(rpm -q --queryformat '%{SIGMD5}\n' -p ./rpmbuild/RPMS/x86_64/rippled-devel*.rpm 2>/dev/null)
|
||||
REP_MD5SUM=$(rpm -q --queryformat '%{SIGMD5}\n' -p ./rpmbuild/RPMS/x86_64/rippled-reporting*.rpm 2>/dev/null)
|
||||
SRC_MD5SUM=$(rpm -q --queryformat '%{SIGMD5}\n' -p ./rpmbuild/SRPMS/*.rpm 2>/dev/null)
|
||||
|
||||
RPM_SHA256="$(sha256sum ./rpmbuild/RPMS/x86_64/rippled-[0-9]*.rpm | awk '{ print $1}')"
|
||||
DBG_SHA256="$(sha256sum ./rpmbuild/RPMS/x86_64/rippled-debuginfo*.rpm | awk '{ print $1}')"
|
||||
REP_SHA256="$(sha256sum ./rpmbuild/RPMS/x86_64/rippled-reporting*.rpm | awk '{ print $1}')"
|
||||
DEV_SHA256="$(sha256sum ./rpmbuild/RPMS/x86_64/rippled-devel*.rpm | awk '{ print $1}')"
|
||||
SRC_SHA256="$(sha256sum ./rpmbuild/SRPMS/*.rpm | awk '{ print $1}')"
|
||||
|
||||
echo "rpm_md5sum=$RPM_MD5SUM" > ${PKG_OUTDIR}/build_vars
|
||||
echo "rep_md5sum=$REP_MD5SUM" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dbg_md5sum=$DBG_MD5SUM" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dev_md5sum=$DEV_MD5SUM" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "src_md5sum=$SRC_MD5SUM" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "rpm_sha256=$RPM_SHA256" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "rep_sha256=$REP_SHA256" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dbg_sha256=$DBG_SHA256" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "dev_sha256=$DEV_SHA256" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "src_sha256=$SRC_SHA256" >> ${PKG_OUTDIR}/build_vars
|
||||
@@ -77,3 +73,4 @@ echo "rippled_version=$RIPPLED_VERSION" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "rpm_version=$RIPPLED_RPM_VERSION" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "rpm_file_name=$tar_file" >> ${PKG_OUTDIR}/build_vars
|
||||
echo "rpm_version_release=$RPM_VERSION_RELEASE" >> ${PKG_OUTDIR}/build_vars
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
%define rpm_release %(echo $RPM_RELEASE)
|
||||
%define rpm_patch %(echo $RPM_PATCH)
|
||||
%define _prefix /opt/ripple
|
||||
|
||||
Name: rippled
|
||||
# Dashes in Version extensions must be converted to underscores
|
||||
Version: %{rippled_version}
|
||||
@@ -26,41 +25,29 @@ Requires: zlib-static
|
||||
%description devel
|
||||
core library for development of standalone applications that sign transactions.
|
||||
|
||||
%package reporting
|
||||
Summary: Reporting Server for rippled
|
||||
|
||||
%description reporting
|
||||
History server for XRP Ledger
|
||||
|
||||
%prep
|
||||
%setup -c -n rippled
|
||||
|
||||
%build
|
||||
cd rippled
|
||||
mkdir -p bld.rippled
|
||||
pushd bld.rippled
|
||||
cmake .. -G Ninja -DCMAKE_INSTALL_PREFIX=%{_prefix} -DCMAKE_BUILD_TYPE=Release -Dunity=OFF -Dstatic=true -DCMAKE_VERBOSE_MAKEFILE=OFF -Dvalidator_keys=ON
|
||||
cmake --build . --parallel $(nproc) --target rippled --target validator-keys
|
||||
popd
|
||||
|
||||
mkdir -p bld.rippled-reporting
|
||||
cd bld.rippled-reporting
|
||||
cmake .. -G Ninja -DCMAKE_INSTALL_PREFIX=%{_prefix}-reporting -DCMAKE_BUILD_TYPE=Release -Dunity=OFF -Dstatic=true -DCMAKE_VERBOSE_MAKEFILE=OFF -Dreporting=ON
|
||||
cmake --build . --parallel $(nproc) --target rippled
|
||||
mkdir -p bld.release
|
||||
cd bld.release
|
||||
cmake .. -G Ninja -DCMAKE_INSTALL_PREFIX=%{_prefix} -DCMAKE_BUILD_TYPE=Release -Dstatic=true -Dunity=OFF -DCMAKE_VERBOSE_MAKEFILE=OFF -Dvalidator_keys=ON
|
||||
cmake --build . --parallel --target rippled --target validator-keys
|
||||
|
||||
%pre
|
||||
test -e /etc/pki/tls || { mkdir -p /etc/pki; ln -s /usr/lib/ssl /etc/pki/tls; }
|
||||
|
||||
%install
|
||||
rm -rf $RPM_BUILD_ROOT
|
||||
DESTDIR=$RPM_BUILD_ROOT cmake --build rippled/bld.rippled --target install -- -v
|
||||
DESTDIR=$RPM_BUILD_ROOT cmake --build rippled/bld.release --target install
|
||||
rm -rf ${RPM_BUILD_ROOT}/%{_prefix}/lib64/cmake/date
|
||||
install -d ${RPM_BUILD_ROOT}/etc/opt/ripple
|
||||
install -d ${RPM_BUILD_ROOT}/usr/local/bin
|
||||
ln -s %{_prefix}/etc/rippled.cfg ${RPM_BUILD_ROOT}/etc/opt/ripple/rippled.cfg
|
||||
ln -s %{_prefix}/etc/validators.txt ${RPM_BUILD_ROOT}/etc/opt/ripple/validators.txt
|
||||
ln -s %{_prefix}/bin/rippled ${RPM_BUILD_ROOT}/usr/local/bin/rippled
|
||||
install -D rippled/bld.rippled/validator-keys/validator-keys ${RPM_BUILD_ROOT}%{_bindir}/validator-keys
|
||||
install -D rippled/bld.release/validator-keys/validator-keys ${RPM_BUILD_ROOT}%{_bindir}/validator-keys
|
||||
install -D ./rippled/Builds/containers/shared/rippled.service ${RPM_BUILD_ROOT}/usr/lib/systemd/system/rippled.service
|
||||
install -D ./rippled/Builds/containers/packaging/rpm/50-rippled.preset ${RPM_BUILD_ROOT}/usr/lib/systemd/system-preset/50-rippled.preset
|
||||
install -D ./rippled/Builds/containers/shared/update-rippled.sh ${RPM_BUILD_ROOT}%{_bindir}/update-rippled.sh
|
||||
@@ -70,27 +57,7 @@ install -D ./rippled/Builds/containers/shared/rippled-logrotate ${RPM_BUILD_ROOT
|
||||
install -d $RPM_BUILD_ROOT/var/log/rippled
|
||||
install -d $RPM_BUILD_ROOT/var/lib/rippled
|
||||
|
||||
# reporting mode
|
||||
%define _prefix /opt/rippled-reporting
|
||||
mkdir -p ${RPM_BUILD_ROOT}/etc/opt/rippled-reporting/
|
||||
install -D rippled/bld.rippled-reporting/rippled-reporting ${RPM_BUILD_ROOT}%{_bindir}/rippled-reporting
|
||||
install -D ./rippled/cfg/rippled-reporting.cfg ${RPM_BUILD_ROOT}%{_prefix}/etc/rippled-reporting.cfg
|
||||
install -D ./rippled/cfg/validators-example.txt ${RPM_BUILD_ROOT}%{_prefix}/etc/validators.txt
|
||||
install -D ./rippled/Builds/containers/packaging/rpm/50-rippled-reporting.preset ${RPM_BUILD_ROOT}/usr/lib/systemd/system-preset/50-rippled-reporting.preset
|
||||
ln -s %{_prefix}/bin/rippled-reporting ${RPM_BUILD_ROOT}/usr/local/bin/rippled-reporting
|
||||
ln -s %{_prefix}/etc/rippled-reporting.cfg ${RPM_BUILD_ROOT}/etc/opt/rippled-reporting/rippled-reporting.cfg
|
||||
ln -s %{_prefix}/etc/validators.txt ${RPM_BUILD_ROOT}/etc/opt/rippled-reporting/validators.txt
|
||||
install -d $RPM_BUILD_ROOT/var/log/rippled-reporting
|
||||
install -d $RPM_BUILD_ROOT/var/lib/rippled-reporting
|
||||
install -D ./rippled/Builds/containers/shared/rippled-reporting.service ${RPM_BUILD_ROOT}/usr/lib/systemd/system/rippled-reporting.service
|
||||
sed -E 's/rippled?/rippled-reporting/g' ./rippled/Builds/containers/shared/update-rippled.sh > ${RPM_BUILD_ROOT}%{_bindir}/update-rippled-reporting.sh
|
||||
sed -E 's/rippled?/rippled-reporting/g' ./rippled/bin/getRippledInfo > ${RPM_BUILD_ROOT}%{_bindir}/getRippledReportingInfo
|
||||
sed -E 's/rippled?/rippled-reporting/g' ./rippled/Builds/containers/shared/update-rippled-cron > ${RPM_BUILD_ROOT}%{_prefix}/etc/update-rippled-reporting-cron
|
||||
sed -E 's/rippled?/rippled-reporting/g' ./rippled/Builds/containers/shared/rippled-logrotate > ${RPM_BUILD_ROOT}/etc/logrotate.d/rippled-reporting
|
||||
|
||||
|
||||
%post
|
||||
%define _prefix /opt/ripple
|
||||
USER_NAME=rippled
|
||||
GROUP_NAME=rippled
|
||||
|
||||
@@ -108,25 +75,7 @@ chmod 644 %{_prefix}/etc/update-rippled-cron
|
||||
chmod 644 /etc/logrotate.d/rippled
|
||||
chown -R root:$GROUP_NAME %{_prefix}/etc/update-rippled-cron
|
||||
|
||||
%post reporting
|
||||
%define _prefix /opt/rippled-reporting
|
||||
USER_NAME=rippled-reporting
|
||||
GROUP_NAME=rippled-reporting
|
||||
|
||||
getent passwd $USER_NAME &>/dev/null || useradd -r $USER_NAME
|
||||
getent group $GROUP_NAME &>/dev/null || groupadd $GROUP_NAME
|
||||
|
||||
chown -R $USER_NAME:$GROUP_NAME /var/log/rippled-reporting/
|
||||
chown -R $USER_NAME:$GROUP_NAME /var/lib/rippled-reporting/
|
||||
chown -R $USER_NAME:$GROUP_NAME %{_prefix}/
|
||||
|
||||
chmod 755 /var/log/rippled-reporting/
|
||||
chmod 755 /var/lib/rippled-reporting/
|
||||
chmod -x /usr/lib/systemd/system/rippled-reporting.service
|
||||
|
||||
|
||||
%files
|
||||
%define _prefix /opt/ripple
|
||||
%doc rippled/README.md rippled/LICENSE.md
|
||||
%{_bindir}/rippled
|
||||
/usr/local/bin/rippled
|
||||
@@ -149,25 +98,6 @@ chmod -x /usr/lib/systemd/system/rippled-reporting.service
|
||||
%{_prefix}/lib/*.a
|
||||
%{_prefix}/lib/cmake/ripple
|
||||
|
||||
%files reporting
|
||||
%define _prefix /opt/rippled-reporting
|
||||
%doc rippled/README.md rippled/LICENSE.md
|
||||
|
||||
%{_bindir}/rippled-reporting
|
||||
/usr/local/bin/rippled-reporting
|
||||
%config(noreplace) /etc/opt/rippled-reporting/rippled-reporting.cfg
|
||||
%config(noreplace) %{_prefix}/etc/rippled-reporting.cfg
|
||||
%config(noreplace) %{_prefix}/etc/validators.txt
|
||||
%config(noreplace) /etc/opt/rippled-reporting/validators.txt
|
||||
%config(noreplace) /usr/lib/systemd/system/rippled-reporting.service
|
||||
%config(noreplace) /usr/lib/systemd/system-preset/50-rippled-reporting.preset
|
||||
%dir /var/log/rippled-reporting/
|
||||
%dir /var/lib/rippled-reporting/
|
||||
%{_bindir}/update-rippled-reporting.sh
|
||||
%{_bindir}/getRippledReportingInfo
|
||||
%{_prefix}/etc/update-rippled-reporting-cron
|
||||
%config(noreplace) /etc/logrotate.d/rippled-reporting
|
||||
|
||||
%changelog
|
||||
* Wed Aug 28 2019 Mike Ellery <mellery451@gmail.com>
|
||||
- Switch to subproject build for validator-keys
|
||||
|
||||
@@ -30,7 +30,7 @@ cd openssl-${OPENSSL_VER}
|
||||
SSLDIR=$(openssl version -d | cut -d: -f2 | tr -d [:space:]\")
|
||||
./config -fPIC --prefix=/opt/local/openssl --openssldir=${SSLDIR} zlib shared
|
||||
make -j$(nproc) >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make install
|
||||
cd ..
|
||||
rm -f openssl-${OPENSSL_VER}.tar.gz
|
||||
rm -rf openssl-${OPENSSL_VER}
|
||||
@@ -43,7 +43,7 @@ cd libarchive-3.4.1
|
||||
mkdir _bld && cd _bld
|
||||
cmake -DCMAKE_BUILD_TYPE=Release ..
|
||||
make -j$(nproc) >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make install
|
||||
cd ../..
|
||||
rm -f libarchive-3.4.1.tar.gz
|
||||
rm -rf libarchive-3.4.1
|
||||
@@ -55,7 +55,7 @@ cd protobuf-3.10.1
|
||||
./autogen.sh
|
||||
./configure
|
||||
make -j$(nproc) >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make install
|
||||
ldconfig
|
||||
cd ..
|
||||
rm -f protobuf-all-3.10.1.tar.gz
|
||||
@@ -78,7 +78,7 @@ cmake \
|
||||
-DCARES_BUILD_CONTAINER_TESTS=OFF \
|
||||
..
|
||||
make -j$(nproc) >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make install
|
||||
cd ../..
|
||||
rm -f c-ares-1.15.0.tar.gz
|
||||
rm -rf c-ares-1.15.0
|
||||
@@ -98,7 +98,7 @@ cmake \
|
||||
-DProtobuf_USE_STATIC_LIBS=ON \
|
||||
..
|
||||
make -j$(nproc) >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make install
|
||||
cd ../..
|
||||
rm -f xf v1.25.0.tar.gz
|
||||
rm -rf grpc-1.25.0
|
||||
@@ -115,7 +115,7 @@ if [ "${CI_USE}" = true ] ; then
|
||||
cd build
|
||||
cmake -G "Unix Makefiles" ..
|
||||
make -j$(nproc) >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make install
|
||||
cd ../..
|
||||
rm -f Release_1_8_16.tar.gz
|
||||
rm -rf doxygen-Release_1_8_16
|
||||
@@ -136,8 +136,8 @@ if [ "${CI_USE}" = true ] ; then
|
||||
tar xf ccache-3.7.6.tar.gz
|
||||
cd ccache-3.7.6
|
||||
./configure --prefix=/usr/local
|
||||
make >> make_output.txt 2>&1
|
||||
make install >> make_output.txt 2>&1
|
||||
make
|
||||
make install
|
||||
cd ..
|
||||
rm -f ccache-3.7.6.tar.gz
|
||||
rm -rf ccache-3.7.6
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
[Unit]
|
||||
Description=Ripple Daemon
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/opt/rippled-reporting/bin/rippled-reporting --silent --conf /etc/opt/rippled-reporting/rippled-reporting.cfg
|
||||
Restart=on-failure
|
||||
User=rippled-reporting
|
||||
Group=rippled-reporting
|
||||
LimitNOFILE=65536
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -11,10 +11,10 @@ Loop: ripple.app ripple.nodestore
|
||||
ripple.app > ripple.nodestore
|
||||
|
||||
Loop: ripple.app ripple.overlay
|
||||
ripple.overlay ~= ripple.app
|
||||
ripple.overlay == ripple.app
|
||||
|
||||
Loop: ripple.app ripple.peerfinder
|
||||
ripple.app > ripple.peerfinder
|
||||
ripple.peerfinder ~= ripple.app
|
||||
|
||||
Loop: ripple.app ripple.rpc
|
||||
ripple.rpc > ripple.app
|
||||
|
||||
@@ -6,6 +6,7 @@ ripple.app > ripple.crypto
|
||||
ripple.app > ripple.json
|
||||
ripple.app > ripple.protocol
|
||||
ripple.app > ripple.resource
|
||||
ripple.app > ripple.server
|
||||
ripple.app > test.unit_test
|
||||
ripple.basics > ripple.beast
|
||||
ripple.conditions > ripple.basics
|
||||
|
||||
@@ -239,32 +239,3 @@ change the `/opt/local` module path above to match your chosen installation pref
|
||||
`rippled` builds a set of unit tests into the server executable. To run these unit
|
||||
tests after building, pass the `--unittest` option to the compiled `rippled`
|
||||
executable. The executable will exit with summary info after running the unit tests.
|
||||
|
||||
## Workaround for a compile error in soci
|
||||
|
||||
Compilation errors have been observed with Apple Clang 13.1.6+ and soci v4.x. soci compiles with the `-Werror` flag which causes warnings to be treated as errors. These warnings pertain to style (not correctness). However, they cause the cmake process to fail.
|
||||
|
||||
Here's an example of how this looks:
|
||||
```
|
||||
.../rippled/.nih_c/unix_makefiles/AppleClang_13.1.6.13160021/Debug/src/soci/src/core/session.cpp:450:66: note: in instantiation of function template specialization 'soci::use<std::string>' requested here
|
||||
return prepare << backEnd_->get_column_descriptions_query(), use(table_name, "t");
|
||||
^
|
||||
1 error generated.
|
||||
```
|
||||
|
||||
Please apply the below patch (courtesy of Scott Determan) to remove these errors. `.nih_c/unix_makefiles/AppleClang_13.1.6.13160021/Debug/src/soci/cmake/SociConfig.cmake` file needs to be edited. This file is an example for Mac OS and it might be slightly different for other OS/Architectures.
|
||||
|
||||
```
|
||||
diff --git a/cmake/SociConfig.cmake b/cmake/SociConfig.cmake
|
||||
index 97d907e4..11bcd1f3 100644
|
||||
--- a/cmake/SociConfig.cmake
|
||||
+++ b/cmake/SociConfig.cmake
|
||||
@@ -58,8 +58,8 @@ if (MSVC)
|
||||
|
||||
else()
|
||||
|
||||
- set(SOCI_GCC_CLANG_COMMON_FLAGS
|
||||
- "-pedantic -Werror -Wno-error=parentheses -Wall -Wextra -Wpointer-arith -Wcast-align -Wcast-qual -Wfloat-equal -Woverloaded-virtual -Wredundant-decls -Wno-long-long")
|
||||
+ set(SOCI_GCC_CLANG_COMMON_FLAGS "")
|
||||
+ # "-pedantic -Werror -Wno-error=parentheses -Wall -Wextra -Wpointer-arith -Wcast-align -Wcast-qual -Wfloat-equal -Woverloaded-virtual -Wredundant-decls -Wno-long-long")
|
||||
```
|
||||
|
||||
@@ -31,7 +31,12 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Builds/CMake")
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Builds/CMake/deps")
|
||||
|
||||
include (CheckCXXCompilerFlag)
|
||||
include (FetchContent)
|
||||
if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.11)
|
||||
include (FetchContent)
|
||||
endif ()
|
||||
if (MSVC AND CMAKE_VERSION VERSION_LESS 3.12)
|
||||
message (FATAL_ERROR "MSVC requires cmake 3.12 or greater for proper boost support")
|
||||
endif ()
|
||||
include (ExternalProject)
|
||||
include (CMakeFuncs) # must come *after* ExternalProject b/c it overrides one function in EP
|
||||
include (ProcessorCount)
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
# Contributing
|
||||
The XRP Ledger has many and diverse stakeholders, and everyone deserves a chance to contribute meaningful changes to the code that runs the XRPL.
|
||||
To contribute, please:
|
||||
1. Fork the repository under your own user.
|
||||
2. Create a new branch on which to write your changes. Please note that changes which alter transaction processing must be composed via and guarded using [Amendments](https://xrpl.org/amendments.html). Changes which are _read only_ i.e. RPC, or changes which are only refactors and maintain the existing behaviour do not need to be made through an Amendment.
|
||||
3. Write and test your code.
|
||||
4. Ensure that your code compiles with the provided build engine and update the provided build engine as part of your PR where needed and where appropriate.
|
||||
5. Write test cases for your code and include those in `src/test` such that they are runnable from the command line using `./rippled -u`. (Some changes will not be able to be tested this way.)
|
||||
6. Ensure your code passes automated checks (e.g. clang-format and levelization.)
|
||||
7. Squash your commits (i.e. rebase) into as few commits as is reasonable to describe your changes at a high level (typically a single commit for a small change.)
|
||||
8. Open a PR to the main repository onto the _develop_ branch, and follow the provided template.
|
||||
|
||||
# Major Changes
|
||||
If your code change is a major feature, a breaking change or in some other way makes a significant alteration to the way the XRPL will operate, then you must first write an XLS document (XRP Ledger Standard) describing your change.
|
||||
To do this:
|
||||
1. Go to [XLS Standards](https://github.com/XRPLF/XRPL-Standards/discussions).
|
||||
2. Choose the next available standard number.
|
||||
3. Open a discussion with the appropriate title to propose your draft standard.
|
||||
4. Link your XLS in your PR.
|
||||
|
||||
# Style guide
|
||||
This is a non-exhaustive list of recommended style guidelines. These are not always strictly enforced and serve as a way to keep the codebase coherent rather than a set of _thou shalt not_ commandments.
|
||||
|
||||
## Formatting
|
||||
All code must conform to `clang-format` version 10, unless the result would be unreasonably difficult to read or maintain.
|
||||
To change your code to conform use `clang-format -i <your changed files>`.
|
||||
|
||||
## Avoid
|
||||
1. Proliferation of nearly identical code.
|
||||
2. Proliferation of new files and classes.
|
||||
3. Complex inheritance and complex OOP patterns.
|
||||
4. Unmanaged memory allocation and raw pointers.
|
||||
5. Macros and non-trivial templates (unless they add significant value.)
|
||||
6. Lambda patterns (unless these add significant value.)
|
||||
7. CPU or architecture-specific code unless there is a good reason to include it, and where it is used guard it with macros and provide explanatory comments.
|
||||
8. Importing new libraries unless there is a very good reason to do so.
|
||||
|
||||
## Seek to
|
||||
9. Extend functionality of existing code rather than creating new code.
|
||||
10. Prefer readability over terseness where important logic is concerned.
|
||||
11. Inline functions that are not used or are not likely to be used elsewhere in the codebase.
|
||||
12. Use clear and self-explanatory names for functions, variables, structs and classes.
|
||||
13. Use TitleCase for classes, structs and filenames, camelCase for function and variable names, lower case for namespaces and folders.
|
||||
14. Provide as many comments as you feel that a competent programmer would need to understand what your code does.
|
||||
|
||||
# Maintainers
|
||||
Maintainers are ecosystem participants with elevated access to the repository. They are able to push new code, make decisions on when a release should be made, etc.
|
||||
|
||||
## Code Review
|
||||
New contributors' PRs must be reviewed by at least two of the maintainers. Well established prior contributors can be reviewed by a single maintainer.
|
||||
|
||||
## Adding and Removing
|
||||
New maintainers can be proposed by two existing maintainers, subject to a vote by a quorum of the existing maintainers. A minimum of 50% support and a 50% participation is required. In the event of a tie vote, the addition of the new maintainer will be rejected.
|
||||
|
||||
Existing maintainers can resign, or be subject to a vote for removal at the behest of two existing maintainers. A minimum of 60% agreement and 50% participation are required. The XRP Ledger Foundation will have the ability, for cause, to remove an existing maintainer without a vote.
|
||||
|
||||
## Existing Maintainers
|
||||
* [JoelKatz](https://github.com/JoelKatz) (Ripple)
|
||||
* [Manojsdoshi](https://github.com/manojsdoshi) (Ripple)
|
||||
* [N3tc4t](https://github.com/n3tc4t) (XRPL Labs)
|
||||
* [Nikolaos D Bougalis](https://github.com/nbougalis) (Ripple)
|
||||
* [Nixer89](https://github.com/nixer89) (XRP Ledger Foundation)
|
||||
* [RichardAH](https://github.com/RichardAH) (XRPL Labs + XRP Ledger Foundation)
|
||||
* [Seelabs](https://github.com/seelabs) (Ripple)
|
||||
* [Silkjaer](https://github.com/Silkjaer) (XRP Ledger Foundation)
|
||||
* [WietseWind](https://github.com/WietseWind) (XRPL Labs + XRP Ledger Foundation)
|
||||
* [Ximinez](https://github.com/ximinez) (Ripple)
|
||||
94
README.md
94
README.md
@@ -1,3 +1,97 @@
|
||||
# XRP Ledger Side chain Branch
|
||||
|
||||
## Warning
|
||||
|
||||
This is not the main branch of the XRP Ledger. This branch supports side chains
|
||||
on the XRP ledger and integrates an implementation of side chain federators.
|
||||
This is a developers prelease and it should not be used for production or to
|
||||
transfer real value. Consider this "alpha" quality software. There will be bugs.
|
||||
See "Status" for a fuller description.
|
||||
|
||||
The latest production code for the XRP ledger is on the "master" branch.
|
||||
|
||||
Until this branch is merged with the mainline branch, it will periodically be
|
||||
rebased on that branch and force pushed to github.
|
||||
|
||||
## What are side chains?
|
||||
|
||||
Side chains are independent ledgers. They can have their own transaction types,
|
||||
their own UNL list (or even their own consensus algorithm), and their own set of
|
||||
other unique features (like a smart contracts layer). What's special about them
|
||||
is there is a way to transfer assets from the XRP ledger to the side chain, and
|
||||
a way to return those assets back from the side chain to the XRP ledger. Both
|
||||
XRP and issued assets may be exchanged.
|
||||
|
||||
The motivation for creating a side chain is to implement an idea that may not be
|
||||
a great fit for the main XRP ledger, or may take a long time before such a
|
||||
feature is adopted by the main XRP ledger. The advantage of a side chain over a
|
||||
brand new ledger is it allows the side chain to immediate use tokens with real
|
||||
monetary value.
|
||||
|
||||
This implementation is meant to support side chains that are similar to the XRP
|
||||
ledger and use the XRP ledger as the main chain. The idea is to develop a new
|
||||
side chain, first this code will be forked and the new features specific to the
|
||||
new chain will be implemented.
|
||||
|
||||
## Status
|
||||
|
||||
All the functionality needed to build side chains should be complete. However,
|
||||
it has not been well tested or polished.
|
||||
|
||||
In particular, all of the following are built:
|
||||
|
||||
* Cross chain transactions for both XRP and Issued Assets
|
||||
* Refunds if transactions fail
|
||||
* Allowing federators to rejoin a network
|
||||
* Detecting and handling when federators fall too far behind in processing
|
||||
transactions
|
||||
* A python library to easily create configuration files for testing side chains
|
||||
and spin up side chains on a local machine
|
||||
* Python scripts to test side chains
|
||||
* An interactive shell to explore side chain functionality
|
||||
|
||||
The biggest missing pieces are:
|
||||
|
||||
* Testing: While the functionality is there, it has just begun to be tested.
|
||||
There will be bugs. Even horrible and embarrassing bugs. Of course, this will
|
||||
improve as testing progresses.
|
||||
|
||||
* Tooling: There is a python library and an interactive shell that was built to
|
||||
help development. However, these tools are geared to run a test network on a
|
||||
local machine. They are not geared to new users or to production systems.
|
||||
Better tooling is coming.
|
||||
|
||||
* Documentation: There is documentation that describes the technical details of
|
||||
how side chains works, how to run the python scripts to set up side chains on
|
||||
the local machine, and the changes to the configuration files. However, like
|
||||
the tooling, this is not geared to new users or production systems. Better
|
||||
documentation is coming. In particular, good documentation for how to set up a
|
||||
production side chain - or even a test net that doesn't run on a local
|
||||
machine - needs to be written.
|
||||
|
||||
## Getting Started
|
||||
|
||||
See the instructions [here](docs/sidechain/GettingStarted.md) for how to
|
||||
run an interactive shell that will spin up a set of federators on your local
|
||||
machine and allow you to transfer assets between the main chain and a side
|
||||
chain.
|
||||
|
||||
After setting things up and completing a cross chain transaction with the
|
||||
"getting started" script above, it may to useful to browse some other
|
||||
documentation:
|
||||
|
||||
* [This](bin/sidechain/python/README.md) document describes the scripts and
|
||||
python modules used to test and explore side chains on your local machine.
|
||||
|
||||
* [This](docs/sidechain/configFile.md) document describes the new stanzas in the
|
||||
config file needed for side chains.
|
||||
|
||||
* [This](docs/sidechain/federatorAccountSetup.md) document describes how to set
|
||||
up the federator accounts if not using the python scripts.
|
||||
|
||||
* [This](docs/sidechain/design.md) document describes the low-level details for
|
||||
how side chains work.
|
||||
|
||||
# The XRP Ledger
|
||||
|
||||
The [XRP Ledger](https://xrpl.org/) is a decentralized cryptographic ledger powered by a network of peer-to-peer nodes. The XRP Ledger uses a novel Byzantine Fault Tolerant consensus algorithm to settle and record transactions in a secure distributed database without a central operator.
|
||||
|
||||
281
RELEASENOTES.md
281
RELEASENOTES.md
@@ -5,224 +5,7 @@
|
||||
This document contains the release notes for `rippled`, the reference server implementation of the XRP Ledger protocol. To learn more about how to build, run or update a `rippled` server, visit https://xrpl.org/install-rippled.html
|
||||
|
||||
|
||||
Have new ideas? Need help with setting up your node? Come visit us [here](https://github.com/xrplf/rippled/issues/new/choose)
|
||||
|
||||
# Introducing XRP Ledger version 1.9.4
|
||||
|
||||
Version 1.9.4 of `rippled`, the reference implementation of the XRP Ledger protocol is now available. This release introduces an amendment that removes the ability for an NFT issuer to indicate that trust lines should be automatically created for royalty payments from secondary sales of NFTs, in response to a bug report that indicated how this functionality could be abused to mount a denial of service attack against the issuer.
|
||||
|
||||
## Action Required
|
||||
|
||||
This release introduces a new amendment to the XRP Ledger protocol, **`fixRemoveNFTokenAutoTrustLine`** to mitigate a potential denial-of-service attack against NFT issuers that minted NFTs and allowed secondary trading of those NFTs to create trust lines for any asset.
|
||||
|
||||
This amendment is open for voting according to the XRP Ledger's [amendment process](https://xrpl.org/amendments.html), which enables protocol changes following two weeks of >80% support from trusted validators.
|
||||
|
||||
If you operate an XRP Ledger server, then you should upgrade to version 1.9.4 within two weeks, to ensure service continuity. The exact time that protocol changes take effect depends on the voting decisions of the decentralized network.
|
||||
|
||||
For more information about NFTs on the XRP Ledger, see [NFT Conceptual Overview](https://xrpl.org/nft-conceptual-overview.html).
|
||||
|
||||
|
||||
## Install / Upgrade
|
||||
|
||||
On supported platforms, see the [instructions on installing or updating `rippled`](https://xrpl.org/install-rippled.html).
|
||||
|
||||
## Changelog
|
||||
|
||||
## Contributions
|
||||
|
||||
The primary change in this release is the following bug fix:
|
||||
|
||||
- **Introduce fixRemoveNFTokenAutoTrustLine amendment**: Introduces the `fixRemoveNFTokenAutoTrustLine` amendment, which disables the `tfTrustLine` flag, which a malicious attacker could exploit to mount denial-of-service attacks against NFT issuers that specified the flag on their NFTs. ([#4301](https://github.com/XRPLF/rippled/4301))
|
||||
|
||||
|
||||
### GitHub
|
||||
|
||||
The public source code repository for `rippled` is hosted on GitHub at <https://github.com/XRPLF/rippled>.
|
||||
|
||||
We welcome all contributions and invite everyone to join the community of XRP Ledger developers and help us build the Internet of Value.
|
||||
|
||||
### Credits
|
||||
|
||||
The following people contributed directly to this release:
|
||||
|
||||
- Scott Schurr <scott@ripple.com>
|
||||
- Howard Hinnant <howard@ripple.com>
|
||||
- Scott Determan <scott.determan@yahoo.com>
|
||||
- Ikko Ashimine <eltociear@gmail.com>
|
||||
|
||||
|
||||
# Introducing XRP Ledger version 1.9.3
|
||||
|
||||
Version 1.9.3 of `rippled`, the reference server implementation of the XRP Ledger protocol is now available. This release corrects minor technical flaws with the code that loads configured amendment votes after a startup and the copy constructor of `PublicKey`.
|
||||
|
||||
## Install / Upgrade
|
||||
|
||||
On supported platforms, see the [instructions on installing or updating `rippled`](https://xrpl.org/install-rippled.html).
|
||||
|
||||
## Changelog
|
||||
|
||||
## Contributions
|
||||
|
||||
This release contains the following bug fixes:
|
||||
|
||||
- **Change by-value to by-reference to persist vote**: A minor technical flaw, caused by use of a copy instead of a reference, resulted in operator-configured "yes" votes to not be properly loaded after a restart. ([#4256](https://github.com/XRPLF/rippled/pull/4256))
|
||||
- **Properly handle self-assignment of PublicKey**: The `PublicKey` copy assignment operator mishandled the case where a `PublicKey` would be assigned to itself, and could result in undefined behavior.
|
||||
|
||||
### GitHub
|
||||
|
||||
The public source code repository for `rippled` is hosted on GitHub at <https://github.com/XRPLF/rippled>.
|
||||
|
||||
We welcome contributions, big and small, and invite everyone to join the community of XRP Ledger developers and help us build the Internet of Value.
|
||||
|
||||
### Credits
|
||||
|
||||
The following people contributed directly to this release:
|
||||
|
||||
- Howard Hinnant <howard@ripple.com>
|
||||
- Crypto Brad Garlinghouse <cryptobradgarlinghouse@protonmail.com>
|
||||
- Wo Jake <87929946+wojake@users.noreply.github.com>
|
||||
|
||||
|
||||
# Introducing XRP Ledger version 1.9.2
|
||||
|
||||
Version 1.9.2 of `rippled`, the reference server implementation of the XRP Ledger protocol, is now available. This release includes several fixes and improvements, including a second new fix amendment to correct a bug in Non-Fungible Tokens (NFTs) code, a new API method for order book changes, less noisy logging, and other small fixes.
|
||||
|
||||
<!-- BREAK -->
|
||||
|
||||
|
||||
## Action Required
|
||||
|
||||
This release introduces a two new amendments to the XRP Ledger protocol. The first, **fixNFTokenNegOffer**, fixes a bug in code associated with the **NonFungibleTokensV1** amendment, originally introduced in [version 1.9.0](https://xrpl.org/blog/2022/rippled-1.9.0.html). The second, **NonFungibleTokensV1_1**, is a "roll-up" amendment that enables the **NonFungibleTokensV1** feature plus the two fix amendments associated with it, **fixNFTokenDirV1** and **fixNFTokenNegOffer**.
|
||||
|
||||
If you want to enable NFT code on the XRP Ledger Mainnet, you can vote in favor of only the **NonFungibleTokensV1_1** amendment to support enabling the feature and fixes together, without risk that the unfixed NFT code may become enabled first.
|
||||
|
||||
These amendments are now open for voting according to the XRP Ledger's [amendment process](https://xrpl.org/amendments.html), which enables protocol changes following two weeks of >80% support from trusted validators.
|
||||
|
||||
If you operate an XRP Ledger server, then you should upgrade to version 1.9.2 within two weeks, to ensure service continuity. The exact time that protocol changes take effect depends on the voting decisions of the decentralized network.
|
||||
|
||||
For more information about NFTs on the XRP Ledger, see [NFT Conceptual Overview](https://xrpl.org/nft-conceptual-overview.html).
|
||||
|
||||
## Install / Upgrade
|
||||
|
||||
On supported platforms, see the [instructions on installing or updating `rippled`](https://xrpl.org/install-rippled.html).
|
||||
|
||||
## Changelog
|
||||
|
||||
This release contains the following features and improvements.
|
||||
|
||||
- **Introduce fixNFTokenNegOffer amendment.** This amendment fixes a bug in the Non-Fungible Tokens (NFTs) functionality provided by the NonFungibleTokensV1 amendment (not currently enabled on Mainnet). The bug allowed users to place offers to buy tokens for negative amounts of money when using Brokered Mode. Anyone who accepted such an offer would transfer the token _and_ pay money. This amendment explicitly disallows offers to buy or sell NFTs for negative amounts of money, and returns an appropriate error code. This also corrects the error code returned when placing offers to buy or sell NFTs for negative amounts in Direct Mode. ([8266d9d](https://github.com/XRPLF/rippled/commit/8266d9d598d19f05e1155956b30ca443c27e119e))
|
||||
- **Introduce `NonFungibleTokensV1_1` amendment.** This amendment encompasses three NFT-related amendments: the original NonFungibleTokensV1 amendment (from version 1.9.0), the fixNFTokenDirV1 amendment (from version 1.9.1), and the new fixNFTokenNegOffer amendment from this release. This amendment contains no changes other than enabling those three amendments together; this allows validators to vote in favor of _only_ enabling the feature and fixes at the same time. ([59326bb](https://github.com/XRPLF/rippled/commit/59326bbbc552287e44b3a0d7b8afbb1ddddb3e3b))
|
||||
- **Handle invalid port numbers.** If the user specifies a URL with an invalid port number, the server would silently attempt to use port 0 instead. Now it raises an error instead. This affects admin API methods and config file parameters for downloading history shards and specifying validator list sites. ([#4213](https://github.com/XRPLF/rippled/pull/4213))
|
||||
- **Reduce log noisiness.** Decreased the severity of benign log messages in several places: "addPathsForType" messages during regular operation, expected errors during unit tests, and missing optional documentation components when compiling from source. ([#4178](https://github.com/XRPLF/rippled/pull/4178), [#4166](https://github.com/XRPLF/rippled/pull/4166), [#4180](https://github.com/XRPLF/rippled/pull/4180))
|
||||
- **Fix race condition in history shard implementation and support clang's ThreadSafetyAnalysis tool.** Added build settings so that developers can use this feature of the clang compiler to analyze the code for correctness, and fix an error found by this tool, which was the source of rare crashes in unit tests. ([#4188](https://github.com/XRPLF/rippled/pull/4188))
|
||||
- **Prevent crash when rotating a database with missing data.** When rotating databases, a missing entry could cause the server to crash. While there should never be a missing database entry, this change keeps the server running by aborting database rotation. ([#4182](https://github.com/XRPLF/rippled/pull/4182))
|
||||
- **Fix bitwise comparison in OfferCreate.** Fixed an expression that incorrectly used a bitwise comparison for two boolean values rather than a true boolean comparison. The outcome of the two comparisons is equivalent, so this is not a transaction processing change, but the bitwise comparison relied on compilers to implicitly fix the expression. ([#4183](https://github.com/XRPLF/rippled/pull/4183))
|
||||
- **Disable cluster timer when not in a cluster.** Disabled a timer that was unused on servers not running in clustered mode. The functionality of clustered servers is unchanged. ([#4173](https://github.com/XRPLF/rippled/pull/4173))
|
||||
- **Limit how often to process peer discovery messages.** In the peer-to-peer network, servers periodically share IP addresses of their peers with each other to facilitate peer discovery. It is not necessary to process these types of messages too often; previously, the code tracked whether it needed to process new messages of this type but always processed them anyway. With this change, the server no longer processes peer discovery messages if it has done so recently. ([#4202](https://github.com/XRPLF/rippled/pull/4202))
|
||||
- **Improve STVector256 deserialization.** Optimized the processing of this data type in protocol messages. This data type is used in several types of ledger entry that are important for bookkeeping, including directory pages that track other ledger types, amendments tracking, and the ledger hashes history. ([#4204](https://github.com/XRPLF/rippled/pull/4204))
|
||||
- **Fix and refactor spinlock code.** The spinlock code, which protects the `SHAMapInnerNode` child lists, had a mistake that allowed the same child to be repeatedly locked under some circumstances. Fixed this bug and improved the spinlock code to make it easier to use correctly and easier to verify that the code works correctly. ([#4201](https://github.com/XRPLF/rippled/pull/4201))
|
||||
- **Improve comments and contributor documentation.** Various minor documentation changes including some to reflect the fact that the source code repository is now owned by the XRP Ledger Foundation. ([#4214](https://github.com/XRPLF/rippled/pull/4214), [#4179](https://github.com/XRPLF/rippled/pull/4179), [#4222](https://github.com/XRPLF/rippled/pull/4222))
|
||||
- **Introduces a new API book_changes to provide information in a format that is useful for building charts that highlight DEX activity at a per-ledger level.** ([#4212](https://github.com/XRPLF/rippled/pull/4212))
|
||||
|
||||
## Contributions
|
||||
|
||||
### GitHub
|
||||
|
||||
The public source code repository for `rippled` is hosted on GitHub at <https://github.com/XRPLF/rippled>.
|
||||
|
||||
We welcome contributions, big and small, and invite everyone to join the community of XRP Ledger developers and help us build the Internet of Value.
|
||||
|
||||
### Credits
|
||||
|
||||
The following people contributed directly to this release:
|
||||
|
||||
- Chenna Keshava B S <ckbs.keshava56@gmail.com>
|
||||
- Ed Hennis <ed@ripple.com>
|
||||
- Ikko Ashimine <eltociear@gmail.com>
|
||||
- Nik Bougalis <nikb@bougalis.net>
|
||||
- Richard Holland <richard.holland@starstone.co.nz>
|
||||
- Scott Schurr <scott@ripple.com>
|
||||
- Scott Determan <scott.determan@yahoo.com>
|
||||
|
||||
For a real-time view of all lifetime contributors, including links to the commits made by each, please visit the "Contributors" section of the GitHub repository: <https://github.com/XRPLF/rippled/graphs/contributors>.
|
||||
|
||||
# Introducing XRP Ledger version 1.9.1
|
||||
|
||||
Version 1.9.1 of `rippled`, the reference server implementation of the XRP Ledger protocol, is now available. This release includes several important fixes, including a fix for a syncing issue from 1.9.0, a new fix amendment to correct a bug in the new Non-Fungible Tokens (NFTs) code, and a new amendment to allow multi-signing by up to 32 signers.
|
||||
|
||||
<!-- BREAK -->
|
||||
|
||||
|
||||
## Action Required
|
||||
|
||||
This release introduces two new amendments to the XRP Ledger protocol. These amendments are now open for voting according to the XRP Ledger's [amendment process](https://xrpl.org/amendments.html), which enables protocol changes following two weeks of >80% support from trusted validators.
|
||||
|
||||
If you operate an XRP Ledger server, then you should upgrade to version 1.9.1 within two weeks, to ensure service continuity. The exact time that protocol changes take effect depends on the voting decisions of the decentralized network.
|
||||
|
||||
The **fixNFTokenDirV1** amendment fixes a bug in code associated with the **NonFungibleTokensV1** amendment, so the fixNFTokenDirV1 amendment should be enabled first. All validator operators are encouraged to [configure amendment voting](https://xrpl.org/configure-amendment-voting.html) to oppose the NonFungibleTokensV1 amendment until _after_ the fixNFTokenDirV1 amendment has become enabled. For more information about NFTs on the XRP Ledger, see [NFT Conceptual Overview](https://xrpl.org/nft-conceptual-overview.html).
|
||||
|
||||
The **ExpandedSignerList** amendment extends the ledger's built-in multi-signing functionality so that each list can contain up to 32 entries instead of the current limit of 8. Additionally, this amendment allows each signer to have an arbitrary 256-bit data field associated with it. This data can be used to identify the signer or provide other metadata that is useful for organizations, smart contracts, or other purposes.
|
||||
|
||||
## Install / Upgrade
|
||||
|
||||
On supported platforms, see the [instructions on installing or updating `rippled`](https://xrpl.org/install-rippled.html).
|
||||
|
||||
## Changelog
|
||||
|
||||
This release contains the following features and improvements.
|
||||
|
||||
## New Features and Amendments
|
||||
|
||||
- **Introduce fixNFTokenDirV1 Amendment** - This amendment fixes an off-by-one error that occurred in some corner cases when determining which `NFTokenPage` an `NFToken` object belongs on. It also adjusts the constraints of `NFTokenPage` invariant checks, so that certain error cases fail with a suitable error code such as `tecNO_SUITABLE_TOKEN_PAGE` instead of failing with a `tecINVARIANT_FAILED` error code. ([#4155](https://github.com/ripple/rippled/pull/4155))
|
||||
|
||||
- **Introduce ExpandedSignerList Amendment** - This amendment expands the maximum signer list size to 32 entries and allows each signer to have an optional 256-bit `WalletLocator` field containing arbitrary data. ([#4097](https://github.com/ripple/rippled/pull/4097))
|
||||
|
||||
- **Pause online deletion rather than canceling it if the server fails health check** - The server stops performing online deletion of old ledger history if the server fails its internal health check during this time. Online deletion can now resume after the server recovers, rather than having to start over. ([#4139](https://github.com/ripple/rippled/pull/4139))
|
||||
|
||||
|
||||
## Bug Fixes and Performance Improvements
|
||||
|
||||
- **Fix performance issues introduced in 1.9.0** - Readjusts some parameters of the ledger acquisition engine to revert some changes introduced in 1.9.0 that had adverse effects on some systems, including causing some systems to fail to sync to the network. ([#4152](https://github.com/ripple/rippled/pull/4152))
|
||||
|
||||
- **Improve Memory Efficiency of Path Finding** - Finding paths for cross-currency payments is a resource-intensive operation. While that remains true, this fix improves memory usage of pathfinding by discarding trust line results that cannot be used before those results are fully loaded or cached. ([#4111](https://github.com/ripple/rippled/pull/4111))
|
||||
|
||||
- **Fix incorrect CMake behavior on Windows when platform is unspecified or x64** - Fixes handling of platform selection when using the cmake-gui tool to build on Windows. The generator expects `Win64` but the GUI only provides `x64` as an option, which raises an error. This fix only raises an error if the platform is `Win32` instead, allowing the generation of solution files to succeed. ([#4150](https://github.com/ripple/rippled/pull/4150))
|
||||
|
||||
- **Fix test failures with newer MSVC compilers on Windows** - Fixes some cases where the API handler code used string pointer comparisons, which may not work correctly with some versions of the MSVC compiler. ([#4149](https://github.com/ripple/rippled/pull/4149))
|
||||
|
||||
- **Update minimum Boost version to 1.71.0** - This release is compatible with Boost library versions 1.71.0 through 1.77.0. The build configuration and documentation have been updated to reflect this. ([#4134](https://github.com/ripple/rippled/pull/4134))
|
||||
|
||||
- **Fix unit test failures for DatabaseDownloader** - Increases a timeout in the `DatabaseDownloader` code and adjusts unit tests so that the code does not return spurious failures, and more data is logged if it does fail. ([#4021](https://github.com/ripple/rippled/pull/4021))
|
||||
|
||||
- **Refactor relational database interface** - Improves code comments, naming, and organization of the module that interfaces with relational databases (such as the SQLite database used for tracking transaction history). ([#3965](https://github.com/ripple/rippled/pull/3965))
|
||||
|
||||
|
||||
## Contributions
|
||||
|
||||
### GitHub
|
||||
|
||||
The public source code repository for `rippled` is hosted on GitHub at <https://github.com/ripple/rippled>.
|
||||
|
||||
We welcome contributions, big and small, and invite everyone to join the community of XRP Ledger developers and help us build the Internet of Value.
|
||||
|
||||
|
||||
### Credits
|
||||
|
||||
The following people contributed directly to this release:
|
||||
|
||||
- Devon White <dwhite@ripple.com>
|
||||
- Ed Hennis <ed@ripple.com>
|
||||
- Gregory Popovitch <greg7mdp@gmail.com>
|
||||
- Mark Travis <mtravis@ripple.com>
|
||||
- Manoj Doshi <mdoshi@ripple.com>
|
||||
- Nik Bougalis <nikb@bougalis.net>
|
||||
- Richard Holland <richard.holland@starstone.co.nz>
|
||||
- Scott Schurr <scott@ripple.com>
|
||||
|
||||
For a real-time view of all lifetime contributors, including links to the commits made by each, please visit the "Contributors" section of the GitHub repository: <https://github.com/ripple/rippled/graphs/contributors>.
|
||||
|
||||
We welcome external contributions and are excited to see the broader XRP Ledger community continue to grow and thrive.
|
||||
|
||||
Have new ideas? Need help with setting up your node? Come visit us [here](https://github.com/ripple/rippled/issues/new/choose)
|
||||
|
||||
# Change log
|
||||
|
||||
@@ -230,68 +13,6 @@ We welcome external contributions and are excited to see the broader XRP Ledger
|
||||
|
||||
# Releases
|
||||
|
||||
## Version 1.9.0
|
||||
This is the 1.9.0 release of `rippled`, the reference implementation of the XRP Ledger protocol. This release brings several features and improvements.
|
||||
|
||||
### New and Improved Features
|
||||
- **Introduce NFT support (XLS020):** This release introduces support for non-fungible tokens, currently available to the developer community for broader review and testing. Developers can create applications that allow users to mint, transfer, and ultimately burn (if desired) NFTs on the XRP Ledger. You can try out the new NFT transactions using the [nft-devnet](https://xrpl.org/xrp-testnet-faucet.html). Note that some fields and error codes from earlier releases of the supporting code have been refactored for this release, shown in the Code Refactoring section, below. [70779f](https://github.com/ripple/rippled/commit/70779f6850b5f33cdbb9cf4129bc1c259af0013e)
|
||||
|
||||
- **Simplify the Job Queue:** This is a refactor aimed at cleaning up and simplifying the existing job queue. Currently, all jobs are canceled at the same time and in the same way, so this commit removes the unnecessary per-job cancellation token. [#3656](https://github.com/ripple/rippled/pull/3656)
|
||||
|
||||
- **Optimize trust line caching:** The existing trust line caching code was suboptimal in that it stored redundant information, pinned SLEs into memory, and required multiple memory allocations per cached object. This commit eliminates redundant data, reduces the size of cached objects and unpinning SLEs from memory, and uses value types to avoid the need for `std::shared_ptr`. As a result of these changes, the effective size of a cached object includes the overhead of the memory allocator, and the `std::shared_ptr` should be reduced by at least 64 bytes. This is significant, as there can easily be tens of millions of these objects. [4d5459](https://github.com/ripple/rippled/commit/4d5459d041da8f5a349c5f458d664e5865e1f1b5)
|
||||
|
||||
- **Incremental improvements to pathfinding memory usage:** This commit aborts background pathfinding when closed or disconnected, exits the pathfinding job thread if there are no requests left, does not create the path find a job if there are no requests, and refactors to remove the circular dependency between InfoSub and PathRequest. [#4111](https://github.com/ripple/rippled/pull/4111)
|
||||
|
||||
- **Improve deterministic transaction sorting in TxQ:** This commit ensures that transactions with the same fee level are sorted by TxID XORed with the parent ledger hash, the TxQ is re-sorted after every ledger, and attempts to future-proof the TxQ tie-breaking test. [#4077](https://github.com/ripple/rippled/pull/4077)
|
||||
|
||||
- **Improve stop signaling for Application:** [34ca45](https://github.com/ripple/rippled/commit/34ca45713244d0defc39549dd43821784b2a5c1d)
|
||||
|
||||
- **Eliminate SHAMapInnerNode lock contention:** The `SHAMapInnerNode` class had a global mutex to protect the array of node children. Profiling suggested that around 4% of all attempts to lock the global would block. This commit removes that global mutex, and replaces it with a new per-node 16-way spinlock (implemented so as not to affect the size of an inner node object), effectively eliminating the lock contention. [1b9387](https://github.com/ripple/rippled/commit/1b9387eddc1f52165d3243d2ace9be0c62495eea)
|
||||
|
||||
- **Improve ledger-fetching logic:** When fetching ledgers, the existing code would isolate the peer that sent the most useful responses, and issue follow-up queries only to that peer. This commit increases the query aggressiveness, and changes the mechanism used to select which peers to issue follow-up queries to so as to more evenly spread the load among those peers that provided useful responses. [48803a](https://github.com/ripple/rippled/commit/48803a48afc3bede55d71618c2ee38fd9dbfd3b0)
|
||||
|
||||
- **Simplify and improve order book tracking:** The order book tracking code would use `std::shared_ptr` to track the lifetime of objects. This commit changes the logic to eliminate the overhead of `std::shared_ptr` by using value types, resulting in significant memory savings. [b9903b](https://github.com/ripple/rippled/commit/b9903bbcc483a384decf8d2665f559d123baaba2)
|
||||
|
||||
- **Negative cache support for node store:** This commit allows the cache to service requests for nodes that were previously looked up but not found, reducing the need to perform I/O in several common scenarios. [3eb8aa](https://github.com/ripple/rippled/commit/3eb8aa8b80bd818f04c99cee2cfc243192709667)
|
||||
|
||||
- **Improve asynchronous database handlers:** This commit optimizes the way asynchronous node store operations are processed, both by reducing the number of times locks are held and by minimizing the number of memory allocations and data copying. [6faaa9](https://github.com/ripple/rippled/commit/6faaa91850d6b2eb9fbf16c1256bf7ef11ac4646)
|
||||
|
||||
- **Cleanup AcceptedLedger and AcceptedLedgerTx:** This commit modernizes the `AcceptedLedger` and `AcceptedLedgerTx` classes, reduces their memory footprint, and reduces unnecessary dynamic memory allocations. [8f5868](https://github.com/ripple/rippled/commit/8f586870917818133924bf2e11acab5321c2b588)
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
This release includes name changes in the NFToken API for SFields, RPC return labels, and error codes for clarity and consistency. To refactor your code, migrate the names of these items to the new names as listed below.
|
||||
|
||||
#### `SField` name changes:
|
||||
* `TokenTaxon -> NFTokenTaxon`
|
||||
* `MintedTokens -> MintedNFTokens`
|
||||
* `BurnedTokens -> BurnedNFTokens`
|
||||
* `TokenID -> NFTokenID`
|
||||
* `TokenOffers -> NFTokenOffers`
|
||||
* `BrokerFee -> NFTokenBrokerFee`
|
||||
* `Minter -> NFTokenMinter`
|
||||
* `NonFungibleToken -> NFToken`
|
||||
* `NonFungibleTokens -> NFTokens`
|
||||
* `BuyOffer -> NFTokenBuyOffer`
|
||||
* `SellOffer -> NFTokenSellOffer`
|
||||
* `OfferNode -> NFTokenOfferNode`
|
||||
|
||||
#### RPC return labels
|
||||
* `tokenid -> nft_id`
|
||||
* `index -> nft_offer_index`
|
||||
|
||||
#### Error codes
|
||||
* `temBAD_TRANSFER_FEE -> temBAD_NFTOKEN_TRANSFER_FEE`
|
||||
* `tefTOKEN_IS_NOT_TRANSFERABLE -> tefNFTOKEN_IS_NOT_TRANSFERABLE`
|
||||
* `tecNO_SUITABLE_PAGE -> tecNO_SUITABLE_NFTOKEN_PAGE`
|
||||
* `tecBUY_SELL_MISMATCH -> tecNFTOKEN_BUY_SELL_MISMATCH`
|
||||
* `tecOFFER_TYPE_MISMATCH -> tecNFTOKEN_OFFER_TYPE_MISMATCH`
|
||||
* `tecCANT_ACCEPT_OWN_OFFER -> tecCANT_ACCEPT_OWN_NFTOKEN_OFFER`
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
- **Fix deletion of orphan node store directories:** Orphaned node store directories should only be deleted if the proper node store directories are confirmed to exist. [06e87e](https://github.com/ripple/rippled/commit/06e87e0f6add5b880d647e14ab3d950decfcf416)
|
||||
|
||||
## Version 1.8.5
|
||||
This is the 1.8.5 release of `rippled`, the reference implementation of the XRP Ledger protocol. This release includes fixes and updates for stability and security, and improvements to build scripts. There are no user-facing API or protocol changes in this release.
|
||||
|
||||
|
||||
183
bin/sidechain/python/README.md
Normal file
183
bin/sidechain/python/README.md
Normal file
@@ -0,0 +1,183 @@
|
||||
## Introduction
|
||||
|
||||
This directory contains python scripts to tests and explore side chains.
|
||||
|
||||
See the instructions [here](docs/sidechain/GettingStarted.md) for how to install
|
||||
the necessary dependencies and run an interactive shell that will spin up a set
|
||||
of federators on your local machine and allow you to transfer assets between the
|
||||
main chain and a side chain.
|
||||
|
||||
For all these scripts, make sure the `RIPPLED_MAINCHAIN_EXE`,
|
||||
`RIPPLED_SIDECHAIN_EXE`, and `RIPPLED_SIDECHAIN_CFG_DIR` environment variables
|
||||
are correctly set, and the side chain configuration files exist. Also make sure the python
|
||||
dependencies are installed and the virtual environment is activated.
|
||||
|
||||
Note: the unit tests do not use the configuration files, so the `RIPPLED_SIDECHAIN_CFG_DIR` is
|
||||
not needed for that script.
|
||||
|
||||
## Unit tests
|
||||
|
||||
The "tests" directory contains a simple unit test. It take several minutes to
|
||||
run, and will create the necessary configuration files, start a test main chain
|
||||
in standalone mode, and a test side chain with 5 federators, and do some simple
|
||||
cross chain transactions. Side chains do not yet have extensive tests. Testing
|
||||
is being actively worked on.
|
||||
|
||||
To run the tests, change directories to the `bin/sidechain/python/tests` directory and type:
|
||||
```
|
||||
pytest
|
||||
```
|
||||
|
||||
To capture logging information and to set the log level (to help with debugging), type this instead:
|
||||
```
|
||||
pytest --log-file=log.txt --log-file-level=info
|
||||
```
|
||||
|
||||
The response should be something like the following:
|
||||
```
|
||||
============================= test session starts ==============================
|
||||
platform linux -- Python 3.8.5, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
|
||||
rootdir: /home/swd/projs/ripple/mine/bin/sidechain/python/tests
|
||||
collected 1 item
|
||||
|
||||
simple_xchain_transfer_test.py . [100%]
|
||||
|
||||
======================== 1 passed in 215.20s (0:03:35) =========================
|
||||
|
||||
```
|
||||
|
||||
## Scripts
|
||||
### riplrepl.py
|
||||
|
||||
This is an interactive shell for experimenting with side chains. It will spin up
|
||||
a test main chain running in standalone mode, and a test side chain with five
|
||||
federators - all running on the local machine. There are commands to make
|
||||
payments within a chain, make cross chain payments, check balances, check server
|
||||
info, and check federator info. There is a simple "help" system, but more
|
||||
documentation is needed for this tool (or more likely we need to replace this
|
||||
with some web front end).
|
||||
|
||||
Note: a "repl" is another name for an interactive shell. It stands for
|
||||
"read-eval-print-loop". It is pronounced "rep-ul".
|
||||
|
||||
### create_config_file.py
|
||||
|
||||
This is a script used to create the config files needed to run a test side chain
|
||||
on your local machine. To run this, make sure the rippled is built,
|
||||
`RIPPLED_MAINCHAIN_EXE`, `RIPPLED_SIDECHAIN_EXE`, and
|
||||
`RIPPLED_SIDECHAIN_CFG_DIR` environment variables are correctly set, and the
|
||||
side chain configuration files exist. Also make sure the python dependencies are
|
||||
installed and the virtual environment is activated. Running this will create
|
||||
config files in the directory specified by the `RIPPLED_SIDECHAIN_CFG_DIR`
|
||||
environment variable.
|
||||
|
||||
### log_analyzer.py
|
||||
|
||||
This is a script used to take structured log files and convert them to json for easier debugging.
|
||||
|
||||
## Python modules
|
||||
|
||||
### sidechain.py
|
||||
|
||||
A python module that can be used to write python scripts to interact with
|
||||
side chains. This is used to write unit tests and the interactive shell. To write
|
||||
a standalone script, look at how the tests are written in
|
||||
`test/simple_xchain_transfer_test.py`. The idea is to call
|
||||
`sidechain._multinode_with_callback`, which sets up the two chains, and place
|
||||
your code in the callback. For example:
|
||||
|
||||
```
|
||||
def multinode_test(params: Params):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
my_function(mc_app, sc_app, params)
|
||||
|
||||
sidechain._multinode_with_callback(params,
|
||||
callback,
|
||||
setup_user_accounts=False)
|
||||
```
|
||||
|
||||
The functions `sidechain.main_to_side_transfer` and
|
||||
`sidechain.side_to_main_transfer` can be used as convenience functions to initiate
|
||||
cross chain transfers. Of course, these transactions can also be initiated with
|
||||
a payment to the door account with the memo data set to the destination account
|
||||
on the destination chain (which is what those convenience functions do under the
|
||||
hood).
|
||||
|
||||
Transactions execute asynchonously. Use the function
|
||||
`test_utils.wait_for_balance_change` to ensure a transaction has completed.
|
||||
|
||||
### transaction.py
|
||||
|
||||
A python module for transactions. Currently there are transactions for:
|
||||
|
||||
* Payment
|
||||
* Trust (trust set)
|
||||
* SetRegularKey
|
||||
* SignerLisetSet
|
||||
* AccountSet
|
||||
* Offer
|
||||
* Ticket
|
||||
* Hook (experimental - useful paying with the hook amendment from XRPL Labs).
|
||||
|
||||
Typically, a transaction is submitted through the call operator on an `App` object. For example, to make a payment from the account `alice` to the account `bob` for 500 XRP:
|
||||
```
|
||||
mc_app(Payment(account=alice, dst=bob, amt=XRP(500)))
|
||||
```
|
||||
(where mc_app is an App object representing the main chain).
|
||||
|
||||
### command.py
|
||||
|
||||
A python module for RPC commands. Currently there are commands for:
|
||||
* PathFind
|
||||
* Sign
|
||||
* LedgerAccept (for standalone mode)
|
||||
* Stop
|
||||
* LogLevel
|
||||
* WalletPropose
|
||||
* ValidationCreate
|
||||
* AccountInfo
|
||||
* AccountLines
|
||||
* AccountTx
|
||||
* BookOffers
|
||||
* BookSubscription
|
||||
* ServerInfo
|
||||
* FederatorInfo
|
||||
* Subscribe
|
||||
|
||||
### common.py
|
||||
|
||||
Python module for common ledger objects, including:
|
||||
* Account
|
||||
* Asset
|
||||
* Path
|
||||
* Pathlist
|
||||
|
||||
### app.py
|
||||
|
||||
Python module for an application. An application is responsible for local
|
||||
network (or single server) and an address book that maps aliases to accounts.
|
||||
|
||||
### config_file.py
|
||||
|
||||
Python module representing a config file that is read from disk.
|
||||
|
||||
### interactive.py
|
||||
|
||||
Python module with the implementation of the RiplRepl interactive shell.
|
||||
|
||||
### ripple_client.py
|
||||
|
||||
A python module representing a rippled server.
|
||||
|
||||
### testnet.py
|
||||
|
||||
A python module representing a rippled testnet running on the local machine.
|
||||
|
||||
## Other
|
||||
### requirements.txt
|
||||
|
||||
These are the python dependencies needed by the scripts. Use `pip3 install -r
|
||||
requirements.txt` to install them. A python virtual environment is recommended.
|
||||
See the instructions [here](docs/sidechain/GettingStarted.md) for how to install
|
||||
the dependencies.
|
||||
|
||||
624
bin/sidechain/python/app.py
Normal file
624
bin/sidechain/python/app.py
Normal file
@@ -0,0 +1,624 @@
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pandas as pd
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Callable, Dict, List, Optional, Set, Union
|
||||
|
||||
from ripple_client import RippleClient
|
||||
from common import Account, Asset, XRP
|
||||
from command import AccountInfo, AccountLines, BookOffers, Command, FederatorInfo, LedgerAccept, Sign, Submit, SubscriptionCommand, WalletPropose
|
||||
from config_file import ConfigFile
|
||||
import testnet
|
||||
from transaction import Payment, Transaction
|
||||
|
||||
|
||||
class KeyManager:
|
||||
def __init__(self):
|
||||
self._aliases = {} # alias -> account
|
||||
self._accounts = {} # account id -> account
|
||||
|
||||
def add(self, account: Account) -> bool:
|
||||
if account.nickname:
|
||||
self._aliases[account.nickname] = account
|
||||
self._accounts[account.account_id] = account
|
||||
|
||||
def is_alias(self, name: str):
|
||||
return name in self._aliases
|
||||
|
||||
def account_from_alias(self, name: str) -> Account:
|
||||
assert name in self._aliases
|
||||
return self._aliases[name]
|
||||
|
||||
def known_accounts(self) -> List[Account]:
|
||||
return list(self._accounts.values())
|
||||
|
||||
def account_id_dict(self) -> Dict[str, Account]:
|
||||
return self._accounts
|
||||
|
||||
def alias_or_account_id(self, id: Union[Account, str]) -> str:
|
||||
'''
|
||||
return the alias if it exists, otherwise return the id
|
||||
'''
|
||||
if isinstance(id, Account):
|
||||
return id.alias_or_account_id()
|
||||
|
||||
if id in self._accounts:
|
||||
return self._accounts[id].nickname
|
||||
return id
|
||||
|
||||
def alias_to_account_id(self, alias: str) -> Optional[str]:
|
||||
if id in self._aliases:
|
||||
return self._aliases[id].account_id
|
||||
return None
|
||||
|
||||
def to_string(self, nickname: Optional[str] = None):
|
||||
names = []
|
||||
account_ids = []
|
||||
if nickname:
|
||||
names = [nickname]
|
||||
if nickname in self._aliases:
|
||||
account_ids = [self._aliases[nickname].account_id]
|
||||
else:
|
||||
account_id = ['NA']
|
||||
else:
|
||||
for (k, v) in self._aliases.items():
|
||||
names.append(k)
|
||||
account_ids.append(v.account_id)
|
||||
# use a dataframe to get a nice table output
|
||||
df = pd.DataFrame(data={'name': names, 'id': account_ids})
|
||||
return f'{df.to_string(index=False)}'
|
||||
|
||||
|
||||
class AssetAliases:
|
||||
def __init__(self):
|
||||
self._aliases = {} # alias -> asset
|
||||
|
||||
def add(self, asset: Asset, name: str):
|
||||
self._aliases[name] = asset
|
||||
|
||||
def is_alias(self, name: str):
|
||||
return name in self._aliases
|
||||
|
||||
def asset_from_alias(self, name: str) -> Asset:
|
||||
assert name in self._aliases
|
||||
return self._aliases[name]
|
||||
|
||||
def known_aliases(self) -> List[str]:
|
||||
return list(self._aliases.keys())
|
||||
|
||||
def known_assets(self) -> List[Asset]:
|
||||
return list(self._aliases.values())
|
||||
|
||||
def to_string(self, nickname: Optional[str] = None):
|
||||
names = []
|
||||
currencies = []
|
||||
issuers = []
|
||||
if nickname:
|
||||
names = [nickname]
|
||||
if nickname in self._aliases:
|
||||
v = self._aliases[nickname]
|
||||
currencies = [v.currency]
|
||||
iss = v.issuer if v.issuer else ''
|
||||
issuers = [v.issuer if v.issuer else '']
|
||||
else:
|
||||
currencies = ['NA']
|
||||
issuers = ['NA']
|
||||
else:
|
||||
for (k, v) in self._aliases.items():
|
||||
names.append(k)
|
||||
currencies.append(v.currency)
|
||||
issuers.append(v.issuer if v.issuer else '')
|
||||
# use a dataframe to get a nice table output
|
||||
df = pd.DataFrame(data={
|
||||
'name': names,
|
||||
'currency': currencies,
|
||||
'issuer': issuers
|
||||
})
|
||||
return f'{df.to_string(index=False)}'
|
||||
|
||||
|
||||
class App:
|
||||
'''App to to interact with rippled servers'''
|
||||
def __init__(self,
|
||||
*,
|
||||
standalone: bool,
|
||||
network: Optional[testnet.Network] = None,
|
||||
client: Optional[RippleClient] = None):
|
||||
if network and client:
|
||||
raise ValueError('Cannot specify both a testnet and client in App')
|
||||
if not network and not client:
|
||||
raise ValueError('Must specify a testnet or a client in App')
|
||||
|
||||
self.standalone = standalone
|
||||
self.network = network
|
||||
|
||||
if client:
|
||||
self.client = client
|
||||
else:
|
||||
self.client = self.network.get_client(0)
|
||||
|
||||
self.key_manager = KeyManager()
|
||||
self.asset_aliases = AssetAliases()
|
||||
root_account = Account(nickname='root',
|
||||
account_id='rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
|
||||
secret_key='masterpassphrase')
|
||||
self.key_manager.add(root_account)
|
||||
|
||||
def shutdown(self):
|
||||
if self.network:
|
||||
self.network.shutdown()
|
||||
else:
|
||||
self.client.shutdown()
|
||||
|
||||
def send_signed(self, txn: Transaction) -> dict:
|
||||
'''Sign then send the given transaction'''
|
||||
if not txn.account.secret_key:
|
||||
raise ValueError('Cannot sign transaction without secret key')
|
||||
r = self(Sign(txn.account.secret_key, txn.to_cmd_obj()))
|
||||
raw_signed = r['tx_blob']
|
||||
r = self(Submit(raw_signed))
|
||||
logging.info(f'App.send_signed: {json.dumps(r, indent=1)}')
|
||||
return r
|
||||
|
||||
def send_command(self, cmd: Command) -> dict:
|
||||
'''Send the command to the rippled server'''
|
||||
r = self.client.send_command(cmd)
|
||||
logging.info(
|
||||
f'App.send_command : {cmd.cmd_name()} : {json.dumps(r, indent=1)}')
|
||||
return r
|
||||
|
||||
# Need async version to close ledgers from async functions
|
||||
async def async_send_command(self, cmd: Command) -> dict:
|
||||
'''Send the command to the rippled server'''
|
||||
return await self.client.async_send_command(cmd)
|
||||
|
||||
def send_subscribe_command(
|
||||
self,
|
||||
cmd: SubscriptionCommand,
|
||||
callback: Optional[Callable[[dict], None]] = None) -> dict:
|
||||
'''Send the subscription command to the rippled server. If already subscribed, it will unsubscribe'''
|
||||
return self.client.send_subscribe_command(cmd, callback)
|
||||
|
||||
def get_pids(self) -> List[int]:
|
||||
if self.network:
|
||||
return self.network.get_pids()
|
||||
if pid := self.client.get_pid():
|
||||
return [pid]
|
||||
|
||||
def get_running_status(self) -> List[bool]:
|
||||
if self.network:
|
||||
return self.network.get_running_status()
|
||||
if self.client.get_pid():
|
||||
return [True]
|
||||
else:
|
||||
return [False]
|
||||
|
||||
# Get a dict of the server_state, validated_ledger_seq, and complete_ledgers
|
||||
def get_brief_server_info(self) -> dict:
|
||||
if self.network:
|
||||
return self.network.get_brief_server_info()
|
||||
else:
|
||||
ret = {}
|
||||
for (k, v) in self.client.get_brief_server_info().items():
|
||||
ret[k] = [v]
|
||||
return ret
|
||||
|
||||
def servers_start(self,
|
||||
server_indexes: Optional[Union[Set[int],
|
||||
List[int]]] = None,
|
||||
*,
|
||||
extra_args: Optional[List[List[str]]] = None):
|
||||
if self.network:
|
||||
return self.network.servers_start(server_indexes,
|
||||
extra_args=extra_args)
|
||||
else:
|
||||
raise ValueError('Cannot start stand alone server')
|
||||
|
||||
def servers_stop(self,
|
||||
server_indexes: Optional[Union[Set[int],
|
||||
List[int]]] = None):
|
||||
if self.network:
|
||||
return self.network.servers_stop(server_indexes)
|
||||
else:
|
||||
raise ValueError('Cannot stop stand alone server')
|
||||
|
||||
def federator_info(self,
|
||||
server_indexes: Optional[Union[Set[int],
|
||||
List[int]]] = None):
|
||||
# key is server index. value is federator_info result
|
||||
result_dict = {}
|
||||
if self.network:
|
||||
if not server_indexes:
|
||||
server_indexes = [
|
||||
i for i in range(self.network.num_clients())
|
||||
if self.network.is_running(i)
|
||||
]
|
||||
for i in server_indexes:
|
||||
if self.network.is_running(i):
|
||||
result_dict[i] = self.network.get_client(i).send_command(
|
||||
FederatorInfo())
|
||||
else:
|
||||
if 0 in server_indexes:
|
||||
result_dict[0] = self.client.send_command(FederatorInfo())
|
||||
return result_dict
|
||||
|
||||
def __call__(self,
|
||||
to_send: Union[Transaction, Command, SubscriptionCommand],
|
||||
callback: Optional[Callable[[dict], None]] = None,
|
||||
*,
|
||||
insert_seq_and_fee=False) -> dict:
|
||||
'''Call `send_signed` for transactions or `send_command` for commands'''
|
||||
if isinstance(to_send, SubscriptionCommand):
|
||||
return self.send_subscribe_command(to_send, callback)
|
||||
assert callback is None
|
||||
if isinstance(to_send, Transaction):
|
||||
if insert_seq_and_fee:
|
||||
self.insert_seq_and_fee(to_send)
|
||||
return self.send_signed(to_send)
|
||||
if isinstance(to_send, Command):
|
||||
return self.send_command(to_send)
|
||||
raise ValueError(
|
||||
'Expected `to_send` to be either a Transaction, Command, or SubscriptionCommand'
|
||||
)
|
||||
|
||||
def get_configs(self) -> List[str]:
|
||||
if self.network:
|
||||
return self.network.get_configs()
|
||||
return [self.client.config]
|
||||
|
||||
def create_account(self, name: str) -> Account:
|
||||
''' Create an account. Use the name as the alias. '''
|
||||
if name == 'root':
|
||||
return
|
||||
assert not self.key_manager.is_alias(name)
|
||||
|
||||
account = Account(nickname=name, result_dict=self(WalletPropose()))
|
||||
self.key_manager.add(account)
|
||||
return account
|
||||
|
||||
def create_accounts(self,
|
||||
names: List[str],
|
||||
funding_account: Union[Account, str] = 'root',
|
||||
amt: Union[int, Asset] = 1000000000) -> List[Account]:
|
||||
'''Fund the accounts with nicknames 'names' by using the funding account and amt'''
|
||||
accounts = [self.create_account(n) for n in names]
|
||||
if not isinstance(funding_account, Account):
|
||||
org_funding_account = funding_account
|
||||
funding_account = self.key_manager.account_from_alias(
|
||||
funding_account)
|
||||
if not isinstance(funding_account, Account):
|
||||
raise ValueError(
|
||||
f'Could not find funding account {org_funding_account}')
|
||||
if not isinstance(amt, Asset):
|
||||
assert isinstance(amt, int)
|
||||
amt = Asset(value=amt)
|
||||
for a in accounts:
|
||||
p = Payment(account=funding_account, dst=a, amt=amt)
|
||||
self.send_signed(p)
|
||||
return accounts
|
||||
|
||||
def maybe_ledger_accept(self):
|
||||
if not self.standalone:
|
||||
return
|
||||
self(LedgerAccept())
|
||||
|
||||
# Need async version to close ledgers from async functions
|
||||
async def async_maybe_ledger_accept(self):
|
||||
if not self.standalone:
|
||||
return
|
||||
await self.async_send_command(LedgerAccept())
|
||||
|
||||
def get_balances(
|
||||
self,
|
||||
account: Union[Account, List[Account], None] = None,
|
||||
asset: Union[Asset, List[Asset]] = Asset()
|
||||
) -> pd.DataFrame:
|
||||
'''Return a pandas dataframe of account balances. If account is None, treat as a wildcard (use address book)'''
|
||||
if account is None:
|
||||
account = self.key_manager.known_accounts()
|
||||
if isinstance(account, list):
|
||||
result = [self.get_balances(acc, asset) for acc in account]
|
||||
return pd.concat(result, ignore_index=True)
|
||||
if isinstance(asset, list):
|
||||
result = [self.get_balances(account, ass) for ass in asset]
|
||||
return pd.concat(result, ignore_index=True)
|
||||
if asset.is_xrp():
|
||||
try:
|
||||
df = self.get_account_info(account)
|
||||
except:
|
||||
# Most likely the account does not exist on the ledger. Give a balance of zero.
|
||||
df = pd.DataFrame({
|
||||
'account': [account],
|
||||
'balance': [0],
|
||||
'flags': [0],
|
||||
'owner_count': [0],
|
||||
'previous_txn_id': ['NA'],
|
||||
'previous_txn_lgr_seq': [-1],
|
||||
'sequence': [-1]
|
||||
})
|
||||
df = df.assign(currency='XRP', peer='', limit='')
|
||||
return df.loc[:,
|
||||
['account', 'balance', 'currency', 'peer', 'limit']]
|
||||
else:
|
||||
try:
|
||||
df = self.get_trust_lines(account)
|
||||
if df.empty: return df
|
||||
df = df[(df['peer'] == asset.issuer.account_id)
|
||||
& (df['currency'] == asset.currency)]
|
||||
except:
|
||||
# Most likely the account does not exist on the ledger. Return an empty data frame
|
||||
df = pd.DataFrame({
|
||||
'account': [],
|
||||
'balance': [],
|
||||
'currency': [],
|
||||
'peer': [],
|
||||
'limit': [],
|
||||
})
|
||||
return df.loc[:,
|
||||
['account', 'balance', 'currency', 'peer', 'limit']]
|
||||
|
||||
def get_balance(self, account: Account, asset: Asset) -> Asset:
|
||||
'''Get a balance from a single account in a single asset'''
|
||||
try:
|
||||
df = self.get_balances(account, asset)
|
||||
return asset(df.iloc[0]['balance'])
|
||||
except:
|
||||
return asset(0)
|
||||
|
||||
def get_account_info(self,
|
||||
account: Optional[Account] = None) -> pd.DataFrame:
|
||||
'''Return a pandas dataframe of account info. If account is None, treat as a wildcard (use address book)'''
|
||||
if account is None:
|
||||
known_accounts = self.key_manager.known_accounts()
|
||||
result = [self.get_account_info(acc) for acc in known_accounts]
|
||||
return pd.concat(result, ignore_index=True)
|
||||
try:
|
||||
result = self.client.send_command(AccountInfo(account))
|
||||
except:
|
||||
# Most likely the account does not exist on the ledger. Give a balance of zero.
|
||||
return pd.DataFrame({
|
||||
'account': [account],
|
||||
'balance': [0],
|
||||
'flags': [0],
|
||||
'owner_count': [0],
|
||||
'previous_txn_id': ['NA'],
|
||||
'previous_txn_lgr_seq': [-1],
|
||||
'sequence': [-1]
|
||||
})
|
||||
if 'account_data' not in result:
|
||||
raise ValueError('Bad result from account_info command')
|
||||
info = result['account_data']
|
||||
for dk in ['LedgerEntryType', 'index']:
|
||||
del info[dk]
|
||||
df = pd.DataFrame([info])
|
||||
df.rename(columns={
|
||||
'Account': 'account',
|
||||
'Balance': 'balance',
|
||||
'Flags': 'flags',
|
||||
'OwnerCount': 'owner_count',
|
||||
'PreviousTxnID': 'previous_txn_id',
|
||||
'PreviousTxnLgrSeq': 'previous_txn_lgr_seq',
|
||||
'Sequence': 'sequence'
|
||||
},
|
||||
inplace=True)
|
||||
df['balance'] = df['balance'].astype(int)
|
||||
return df
|
||||
|
||||
def get_trust_lines(self,
|
||||
account: Account,
|
||||
peer: Optional[Account] = None) -> pd.DataFrame:
|
||||
'''Return a pandas dataframe account trust lines. If peer account is None, treat as a wildcard'''
|
||||
result = self.send_command(AccountLines(account, peer=peer))
|
||||
if 'lines' not in result or 'account' not in result:
|
||||
raise ValueError('Bad result from account_lines command')
|
||||
account = result['account']
|
||||
lines = result['lines']
|
||||
for d in lines:
|
||||
d['peer'] = d['account']
|
||||
d['account'] = account
|
||||
return pd.DataFrame(lines)
|
||||
|
||||
def get_offers(self, taker_pays: Asset, taker_gets: Asset) -> pd.DataFrame:
|
||||
'''Return a pandas dataframe of offers'''
|
||||
result = self.send_command(BookOffers(taker_pays, taker_gets))
|
||||
if 'offers' not in result:
|
||||
raise ValueError('Bad result from book_offers command')
|
||||
|
||||
offers = result['offers']
|
||||
delete_keys = [
|
||||
'BookDirectory', 'BookNode', 'LedgerEntryType', 'OwnerNode',
|
||||
'PreviousTxnID', 'PreviousTxnLgrSeq', 'Sequence', 'index'
|
||||
]
|
||||
for d in offers:
|
||||
for dk in delete_keys:
|
||||
del d[dk]
|
||||
for t in ['TakerPays', 'TakerGets', 'owner_funds']:
|
||||
if 'value' in d[t]:
|
||||
d[t] = d[t]['value']
|
||||
df = pd.DataFrame(offers)
|
||||
df.rename(columns={
|
||||
'Account': 'account',
|
||||
'Flags': 'flags',
|
||||
'TakerGets': 'taker_gets',
|
||||
'TakerPays': 'taker_pays'
|
||||
},
|
||||
inplace=True)
|
||||
return df
|
||||
|
||||
def account_balance(self, account: Account, asset: Asset) -> Asset:
|
||||
'''get the account's balance of the asset'''
|
||||
pass
|
||||
|
||||
def substitute_nicknames(
|
||||
self,
|
||||
df: pd.DataFrame,
|
||||
cols: List[str] = ['account', 'peer']) -> pd.DataFrame:
|
||||
result = df.copy(deep=True)
|
||||
for c in cols:
|
||||
if c not in result:
|
||||
continue
|
||||
result[c] = result[c].map(
|
||||
lambda x: self.key_manager.alias_or_account_id(x))
|
||||
return result
|
||||
|
||||
def add_to_keymanager(self, account: Account):
|
||||
self.key_manager.add(account)
|
||||
|
||||
def is_alias(self, name: str) -> bool:
|
||||
return self.key_manager.is_alias(name)
|
||||
|
||||
def account_from_alias(self, name: str) -> Account:
|
||||
return self.key_manager.account_from_alias(name)
|
||||
|
||||
def known_accounts(self) -> List[Account]:
|
||||
return self.key_manager.known_accounts()
|
||||
|
||||
def known_asset_aliases(self) -> List[str]:
|
||||
return self.asset_aliases.known_aliases()
|
||||
|
||||
def known_iou_assets(self) -> List[Asset]:
|
||||
return self.asset_aliases.known_assets()
|
||||
|
||||
def is_asset_alias(self, name: str) -> bool:
|
||||
return self.asset_aliases.is_alias(name)
|
||||
|
||||
def add_asset_alias(self, asset: Asset, name: str):
|
||||
self.asset_aliases.add(asset, name)
|
||||
|
||||
def asset_from_alias(self, name: str) -> Asset:
|
||||
return self.asset_aliases.asset_from_alias(name)
|
||||
|
||||
def insert_seq_and_fee(self, txn: Transaction):
|
||||
acc_info = self(AccountInfo(txn.account))
|
||||
# TODO: set better fee (Hard code a fee of 15 for now)
|
||||
txn.set_seq_and_fee(acc_info['account_data']['Sequence'], 15)
|
||||
|
||||
def get_client(self) -> RippleClient:
|
||||
return self.client
|
||||
|
||||
|
||||
def balances_dataframe(chains: List[App],
|
||||
chain_names: List[str],
|
||||
account_ids: Optional[List[Account]] = None,
|
||||
assets: List[Asset] = None,
|
||||
in_drops: bool = False):
|
||||
def _removesuffix(self: str, suffix: str) -> str:
|
||||
if suffix and self.endswith(suffix):
|
||||
return self[:-len(suffix)]
|
||||
else:
|
||||
return self[:]
|
||||
|
||||
def _balance_df(chain: App, acc: Optional[Account],
|
||||
asset: Union[Asset, List[Asset]], in_drops: bool):
|
||||
b = chain.get_balances(acc, asset)
|
||||
if not in_drops:
|
||||
b.loc[b['currency'] == 'XRP', 'balance'] /= 1_000_000
|
||||
b = chain.substitute_nicknames(b)
|
||||
b = b.set_index('account')
|
||||
return b
|
||||
|
||||
if account_ids is None:
|
||||
account_ids = [None] * len(chains)
|
||||
|
||||
if assets is None:
|
||||
# XRP and all assets in the assets alias list
|
||||
assets = [[XRP(0)] + c.known_iou_assets() for c in chains]
|
||||
|
||||
dfs = []
|
||||
keys = []
|
||||
for chain, chain_name, acc, asset in zip(chains, chain_names, account_ids,
|
||||
assets):
|
||||
dfs.append(_balance_df(chain, acc, asset, in_drops))
|
||||
keys.append(_removesuffix(chain_name, 'chain'))
|
||||
df = pd.concat(dfs, keys=keys)
|
||||
return df
|
||||
|
||||
|
||||
# Start an app with a single client
|
||||
@contextmanager
|
||||
def single_client_app(*,
|
||||
config: ConfigFile,
|
||||
command_log: Optional[str] = None,
|
||||
server_out=os.devnull,
|
||||
run_server: bool = True,
|
||||
exe: Optional[str] = None,
|
||||
extra_args: Optional[List[str]] = None,
|
||||
standalone=False):
|
||||
'''Start a ripple server and return an app'''
|
||||
try:
|
||||
if extra_args is None:
|
||||
extra_args = []
|
||||
to_run = None
|
||||
app = None
|
||||
client = RippleClient(config=config, command_log=command_log, exe=exe)
|
||||
if run_server:
|
||||
to_run = [client.exe, '--conf', client.config_file_name]
|
||||
if standalone:
|
||||
to_run.append('-a')
|
||||
fout = open(server_out, 'w')
|
||||
p = subprocess.Popen(to_run + extra_args,
|
||||
stdout=fout,
|
||||
stderr=subprocess.STDOUT)
|
||||
client.set_pid(p.pid)
|
||||
print(
|
||||
f'started rippled: config: {client.config_file_name} PID: {p.pid}',
|
||||
flush=True)
|
||||
time.sleep(1.5) # give process time to startup
|
||||
app = App(client=client, standalone=standalone)
|
||||
yield app
|
||||
finally:
|
||||
if app:
|
||||
app.shutdown()
|
||||
if run_server and to_run:
|
||||
subprocess.Popen(to_run + ['stop'],
|
||||
stdout=fout,
|
||||
stderr=subprocess.STDOUT)
|
||||
p.wait()
|
||||
|
||||
|
||||
def configs_for_testnet(config_file_prefix: str) -> List[ConfigFile]:
|
||||
configs = []
|
||||
p = Path(config_file_prefix)
|
||||
dir = p.parent
|
||||
file = p.name
|
||||
file_names = []
|
||||
for f in os.listdir(dir):
|
||||
cfg = os.path.join(dir, f, 'rippled.cfg')
|
||||
if f.startswith(file) and os.path.exists(cfg):
|
||||
file_names.append(cfg)
|
||||
file_names.sort()
|
||||
return [ConfigFile(file_name=f) for f in file_names]
|
||||
|
||||
|
||||
# Start an app for a network with the config files matched by `config_file_prefix*/rippled.cfg`
|
||||
|
||||
|
||||
# Undocumented feature: if the environment variable RIPPLED_SIDECHAIN_RR is set, it is
|
||||
# assumed to point to the rr executable. Sidechain server 0 will then be run under rr.
|
||||
@contextmanager
|
||||
def testnet_app(*,
|
||||
exe: str,
|
||||
configs: List[ConfigFile],
|
||||
command_logs: Optional[List[str]] = None,
|
||||
run_server: Optional[List[bool]] = None,
|
||||
sidechain_rr: Optional[str] = None,
|
||||
extra_args: Optional[List[List[str]]] = None):
|
||||
'''Start a ripple testnet and return an app'''
|
||||
try:
|
||||
app = None
|
||||
network = testnet.Network(exe,
|
||||
configs,
|
||||
command_logs=command_logs,
|
||||
run_server=run_server,
|
||||
with_rr=sidechain_rr,
|
||||
extra_args=extra_args)
|
||||
network.wait_for_validated_ledger()
|
||||
app = App(network=network, standalone=False)
|
||||
yield app
|
||||
finally:
|
||||
if app:
|
||||
app.shutdown()
|
||||
563
bin/sidechain/python/command.py
Normal file
563
bin/sidechain/python/command.py
Normal file
@@ -0,0 +1,563 @@
|
||||
import json
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from common import Account, Asset
|
||||
|
||||
|
||||
class Command:
|
||||
'''Interface for all commands sent to the server'''
|
||||
|
||||
# command id useful for websocket messages
|
||||
next_cmd_id = 1
|
||||
|
||||
def __init__(self):
|
||||
self.cmd_id = Command.next_cmd_id
|
||||
Command.next_cmd_id += 1
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
'''Return the command name for use in a command line'''
|
||||
assert False
|
||||
return ''
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name, json.dumps(self.to_cmd_obj())]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = self.to_cmd_obj()
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''Return an object suitalbe for use in a command (input to json.dumps or similar)'''
|
||||
assert False
|
||||
return {}
|
||||
|
||||
def add_websocket_fields(self, cmd_dict: dict) -> dict:
|
||||
cmd_dict['id'] = self.cmd_id
|
||||
cmd_dict['command'] = self.cmd_name()
|
||||
return cmd_dict
|
||||
|
||||
def _set_flag(self, flag_bit: int, value: bool = True):
|
||||
'''Set or clear the flag bit'''
|
||||
if value:
|
||||
self.flags |= flag_bit
|
||||
else:
|
||||
self.flags &= ~flag_bit
|
||||
return self
|
||||
|
||||
|
||||
class SubscriptionCommand(Command):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
|
||||
class PathFind(Command):
|
||||
'''Rippled ripple_path_find command'''
|
||||
def __init__(self,
|
||||
*,
|
||||
src: Account,
|
||||
dst: Account,
|
||||
amt: Asset,
|
||||
send_max: Optional[Asset] = None,
|
||||
src_currencies: Optional[List[Asset]] = None,
|
||||
ledger_hash: Optional[str] = None,
|
||||
ledger_index: Optional[Union[int, str]] = None):
|
||||
super().__init__()
|
||||
self.src = src
|
||||
self.dst = dst
|
||||
self.amt = amt
|
||||
self.send_max = send_max
|
||||
self.src_currencies = src_currencies
|
||||
self.ledger_hash = ledger_hash
|
||||
self.ledger_index = ledger_index
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'ripple_path_find'
|
||||
|
||||
def add_websocket_fields(self, cmd_dict: dict) -> dict:
|
||||
cmd_dict = super().add_websocket_fields(cmd_dict)
|
||||
cmd_dict['subcommand'] = 'create'
|
||||
return cmd_dict
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''convert to transaction form (suitable for using json.dumps or similar)'''
|
||||
cmd = {
|
||||
'source_account': self.src.account_id,
|
||||
'destination_account': self.dst.account_id,
|
||||
'destination_amount': self.amt.to_cmd_obj()
|
||||
}
|
||||
if self.send_max is not None:
|
||||
cmd['send_max'] = self.send_max.to_cmd_obj()
|
||||
if self.ledger_hash is not None:
|
||||
cmd['ledger_hash'] = self.ledger_hash
|
||||
if self.ledger_index is not None:
|
||||
cmd['ledger_index'] = self.ledger_index
|
||||
if self.src_currencies:
|
||||
c = []
|
||||
for sc in self.src_currencies:
|
||||
d = {'currency': sc.currency, 'issuer': sc.issuer.account_id}
|
||||
c.append(d)
|
||||
cmd['source_currencies'] = c
|
||||
return cmd
|
||||
|
||||
|
||||
class Sign(Command):
|
||||
'''Rippled sign command'''
|
||||
def __init__(self, secret: str, tx: dict):
|
||||
super().__init__()
|
||||
self.tx = tx
|
||||
self.secret = secret
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'sign'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name(), self.secret, f'{json.dumps(self.tx)}']
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {'secret': self.secret, 'tx_json': self.tx}
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class Submit(Command):
|
||||
'''Rippled submit command'''
|
||||
def __init__(self, tx_blob: str):
|
||||
super().__init__()
|
||||
self.tx_blob = tx_blob
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'submit'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name(), self.tx_blob]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {'tx_blob': self.tx_blob}
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class LedgerAccept(Command):
|
||||
'''Rippled ledger_accept command'''
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'ledger_accept'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name()]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {}
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class Stop(Command):
|
||||
'''Rippled stop command'''
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'stop'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name()]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {}
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class LogLevel(Command):
|
||||
'''Rippled log_level command'''
|
||||
def __init__(self, severity: str, *, partition: Optional[str] = None):
|
||||
super().__init__()
|
||||
self.severity = severity
|
||||
self.partition = partition
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'log_level'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
if self.partition is not None:
|
||||
return [self.cmd_name(), self.partition, self.severity]
|
||||
return [self.cmd_name(), self.severity]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {'severity': self.severity}
|
||||
if self.partition is not None:
|
||||
result['partition'] = self.partition
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class WalletPropose(Command):
|
||||
'''Rippled wallet_propose command'''
|
||||
def __init__(self,
|
||||
*,
|
||||
passphrase: Optional[str] = None,
|
||||
seed: Optional[str] = None,
|
||||
seed_hex: Optional[str] = None,
|
||||
key_type: Optional[str] = None):
|
||||
super().__init__()
|
||||
self.passphrase = passphrase
|
||||
self.seed = seed
|
||||
self.seed_hex = seed_hex
|
||||
self.key_type = key_type
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'wallet_propose'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
assert not self.seed and not self.seed_hex and (
|
||||
not self.key_type or self.key_type == 'secp256k1')
|
||||
if self.passphrase:
|
||||
return [self.cmd_name(), self.passphrase]
|
||||
return [self.cmd_name()]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {}
|
||||
if self.seed is not None:
|
||||
result['seed'] = self.seed
|
||||
if self.seed_hex is not None:
|
||||
result['seed_hex'] = self.seed_hex
|
||||
if self.passphrase is not None:
|
||||
result['passphrase'] = self.passphrase
|
||||
if self.key_type is not None:
|
||||
result['key_type'] = self.key_type
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class ValidationCreate(Command):
|
||||
'''Rippled validation_create command'''
|
||||
def __init__(self, *, secret: Optional[str] = None):
|
||||
super().__init__()
|
||||
self.secret = secret
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'validation_create'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
if self.secret:
|
||||
return [self.cmd_name(), self.secret]
|
||||
return [self.cmd_name()]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {}
|
||||
if self.secret is not None:
|
||||
result['secret'] = self.secret
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class AccountInfo(Command):
|
||||
'''Rippled account_info command'''
|
||||
def __init__(self,
|
||||
account: Account,
|
||||
*,
|
||||
strict: Optional[bool] = None,
|
||||
ledger_hash: Optional[str] = None,
|
||||
ledger_index: Optional[Union[str, int]] = None,
|
||||
queue: Optional[bool] = None,
|
||||
signers_list: Optional[bool] = None):
|
||||
super().__init__()
|
||||
self.account = account
|
||||
self.strict = strict
|
||||
self.ledger_hash = ledger_hash
|
||||
self.ledger_index = ledger_index
|
||||
self.queue = queue
|
||||
self.signers_list = signers_list
|
||||
assert not ((ledger_hash is not None) and (ledger_index is not None))
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'account_info'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
result = [self.cmd_name(), self.account.account_id]
|
||||
if self.ledger_index is not None:
|
||||
result.append(self.ledger_index)
|
||||
if self.ledger_hash is not None:
|
||||
result.append(self.ledger_hash)
|
||||
if self.strict is not None:
|
||||
result.append(self.strict)
|
||||
return result
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {'account': self.account.account_id}
|
||||
if self.ledger_index is not None:
|
||||
result['ledger_index'] = self.ledger_index
|
||||
if self.ledger_hash is not None:
|
||||
result['ledger_hash'] = self.ledger_hash
|
||||
if self.strict is not None:
|
||||
result['strict'] = self.strict
|
||||
if self.queue is not None:
|
||||
result['queue'] = self.queue
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class AccountLines(Command):
|
||||
'''Rippled account_lines command'''
|
||||
def __init__(self,
|
||||
account: Account,
|
||||
*,
|
||||
peer: Optional[Account] = None,
|
||||
ledger_hash: Optional[str] = None,
|
||||
ledger_index: Optional[Union[str, int]] = None,
|
||||
limit: Optional[int] = None,
|
||||
marker=None):
|
||||
super().__init__()
|
||||
self.account = account
|
||||
self.peer = peer
|
||||
self.ledger_hash = ledger_hash
|
||||
self.ledger_index = ledger_index
|
||||
self.limit = limit
|
||||
self.marker = marker
|
||||
assert not ((ledger_hash is not None) and (ledger_index is not None))
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'account_lines'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
assert sum(x is None for x in [
|
||||
self.ledger_index, self.ledger_hash, self.limit, self.marker
|
||||
]) == 4
|
||||
result = [self.cmd_name(), self.account.account_id]
|
||||
if self.peer is not None:
|
||||
result.append(self.peer)
|
||||
return result
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {'account': self.account.account_id}
|
||||
if self.peer is not None:
|
||||
result['peer'] = self.peer
|
||||
if self.ledger_index is not None:
|
||||
result['ledger_index'] = self.ledger_index
|
||||
if self.ledger_hash is not None:
|
||||
result['ledger_hash'] = self.ledger_hash
|
||||
if self.limit is not None:
|
||||
result['limit'] = self.limit
|
||||
if self.marker is not None:
|
||||
result['marker'] = self.marker
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class AccountTx(Command):
|
||||
def __init__(self,
|
||||
account: Account,
|
||||
*,
|
||||
limit: Optional[int] = None,
|
||||
marker=None):
|
||||
super().__init__()
|
||||
self.account = account
|
||||
self.limit = limit
|
||||
self.marker = marker
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'account_tx'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
result = [self.cmd_name(), self.account.account_id]
|
||||
return result
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {'account': self.account.account_id}
|
||||
if self.limit is not None:
|
||||
result['limit'] = self.limit
|
||||
if self.marker is not None:
|
||||
result['marker'] = self.marker
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class BookOffers(Command):
|
||||
'''Rippled book_offers command'''
|
||||
def __init__(self,
|
||||
taker_pays: Asset,
|
||||
taker_gets: Asset,
|
||||
*,
|
||||
taker: Optional[Account] = None,
|
||||
ledger_hash: Optional[str] = None,
|
||||
ledger_index: Optional[Union[str, int]] = None,
|
||||
limit: Optional[int] = None,
|
||||
marker=None):
|
||||
super().__init__()
|
||||
self.taker_pays = taker_pays
|
||||
self.taker_gets = taker_gets
|
||||
self.taker = taker
|
||||
self.ledger_hash = ledger_hash
|
||||
self.ledger_index = ledger_index
|
||||
self.limit = limit
|
||||
self.marker = marker
|
||||
assert not ((ledger_hash is not None) and (ledger_index is not None))
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'book_offers'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
assert sum(x is None for x in [
|
||||
self.ledger_index, self.ledger_hash, self.limit, self.marker
|
||||
]) == 4
|
||||
return [
|
||||
self.cmd_name(),
|
||||
self.taker_pays.cmd_str(),
|
||||
self.taker_gets.cmd_str()
|
||||
]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {
|
||||
'taker_pays': self.taker_pays.to_cmd_obj(),
|
||||
'taker_gets': self.taker_gets.to_cmd_obj()
|
||||
}
|
||||
if self.taker is not None:
|
||||
result['taker'] = self.taker.account_id
|
||||
if self.ledger_index is not None:
|
||||
result['ledger_index'] = self.ledger_index
|
||||
if self.ledger_hash is not None:
|
||||
result['ledger_hash'] = self.ledger_hash
|
||||
if self.limit is not None:
|
||||
result['limit'] = self.limit
|
||||
if self.marker is not None:
|
||||
result['marker'] = self.marker
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class BookSubscription:
|
||||
'''Spec for a book in a subscribe command'''
|
||||
def __init__(self,
|
||||
taker_pays: Asset,
|
||||
taker_gets: Asset,
|
||||
*,
|
||||
taker: Optional[Account] = None,
|
||||
snapshot: Optional[bool] = None,
|
||||
both: Optional[bool] = None):
|
||||
self.taker_pays = taker_pays
|
||||
self.taker_gets = taker_gets
|
||||
self.taker = taker
|
||||
self.snapshot = snapshot
|
||||
self.both = both
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''Return an object suitalbe for use in a command'''
|
||||
result = {
|
||||
'taker_pays': self.taker_pays.to_cmd_obj(),
|
||||
'taker_gets': self.taker_gets.to_cmd_obj()
|
||||
}
|
||||
if self.taker is not None:
|
||||
result['taker'] = self.taker.account_id
|
||||
if self.snapshot is not None:
|
||||
result['snapshot'] = self.snapshot
|
||||
if self.both is not None:
|
||||
result['both'] = self.both
|
||||
return result
|
||||
|
||||
|
||||
class ServerInfo(Command):
|
||||
'''Rippled server_info command'''
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'server_info'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name()]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {}
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class FederatorInfo(Command):
|
||||
'''Rippled federator_info command'''
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'federator_info'
|
||||
|
||||
def get_command_line_list(self) -> List[str]:
|
||||
'''Return a list of strings suitable for a command line command for a rippled server'''
|
||||
return [self.cmd_name()]
|
||||
|
||||
def get_websocket_dict(self) -> dict:
|
||||
'''Return a dictionary suitable for converting to json and sending to a rippled server using a websocket'''
|
||||
result = {}
|
||||
return self.add_websocket_fields(result)
|
||||
|
||||
|
||||
class Subscribe(SubscriptionCommand):
|
||||
'''The subscribe method requests periodic notifications from the server
|
||||
when certain events happen. See: https://developers.ripple.com/subscribe.html'''
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
streams: Optional[List[str]] = None,
|
||||
accounts: Optional[List[Account]] = None,
|
||||
accounts_proposed: Optional[List[Account]] = None,
|
||||
account_history_account: Optional[Account] = None,
|
||||
books: Optional[
|
||||
List[BookSubscription]] = None, # taker_pays, taker_gets
|
||||
url: Optional[str] = None,
|
||||
url_username: Optional[str] = None,
|
||||
url_password: Optional[str] = None):
|
||||
super().__init__()
|
||||
self.streams = streams
|
||||
self.accounts = accounts
|
||||
self.account_history_account = account_history_account
|
||||
self.accounts_proposed = accounts_proposed
|
||||
self.books = books
|
||||
self.url = url
|
||||
self.url_username = url_username
|
||||
self.url_password = url_password
|
||||
self.websocket = None
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
if self.websocket:
|
||||
return 'unsubscribe'
|
||||
return 'subscribe'
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
d = {}
|
||||
if self.streams is not None:
|
||||
d['streams'] = self.streams
|
||||
if self.accounts is not None:
|
||||
d['accounts'] = [a.account_id for a in self.accounts]
|
||||
if self.account_history_account is not None:
|
||||
d['account_history_tx_stream'] = {
|
||||
'account': self.account_history_account.account_id
|
||||
}
|
||||
if self.accounts_proposed is not None:
|
||||
d['accounts_proposed'] = [
|
||||
a.account_id for a in self.accounts_proposed
|
||||
]
|
||||
if self.books is not None:
|
||||
d['books'] = [b.to_cmd_obj() for b in self.books]
|
||||
if self.url is not None:
|
||||
d['url'] = self.url
|
||||
if self.url_username is not None:
|
||||
d['url_username'] = self.url_username
|
||||
if self.url_password is not None:
|
||||
d['url_password'] = self.url_password
|
||||
return d
|
||||
256
bin/sidechain/python/common.py
Normal file
256
bin/sidechain/python/common.py
Normal file
@@ -0,0 +1,256 @@
|
||||
import binascii
|
||||
import datetime
|
||||
import logging
|
||||
from typing import List, Optional, Union
|
||||
import pandas as pd
|
||||
import pytz
|
||||
import sys
|
||||
|
||||
EPRINT_ENABLED = True
|
||||
|
||||
|
||||
def disable_eprint():
|
||||
global EPRINT_ENABLED
|
||||
EPRINT_ENABLED = False
|
||||
|
||||
|
||||
def enable_eprint():
|
||||
global EPRINT_ENABLED
|
||||
EPRINT_ENABLED = True
|
||||
|
||||
|
||||
def eprint(*args, **kwargs):
|
||||
if not EPRINT_ENABLED:
|
||||
return
|
||||
logging.error(*args)
|
||||
print(*args, file=sys.stderr, flush=True, **kwargs)
|
||||
|
||||
|
||||
def to_rippled_epoch(d: datetime.datetime) -> int:
|
||||
'''Convert from a datetime to the number of seconds since Jan 1, 2000 (rippled epoch)'''
|
||||
start = datetime.datetime(2000, 1, 1, tzinfo=pytz.utc)
|
||||
return int((d - start).total_seconds())
|
||||
|
||||
|
||||
class Account: # pylint: disable=too-few-public-methods
|
||||
'''
|
||||
Account in the ripple ledger
|
||||
'''
|
||||
def __init__(self,
|
||||
*,
|
||||
account_id: Optional[str] = None,
|
||||
nickname: Optional[str] = None,
|
||||
public_key: Optional[str] = None,
|
||||
public_key_hex: Optional[str] = None,
|
||||
secret_key: Optional[str] = None,
|
||||
result_dict: Optional[dict] = None):
|
||||
self.account_id = account_id
|
||||
self.nickname = nickname
|
||||
self.public_key = public_key
|
||||
self.public_key_hex = public_key_hex
|
||||
self.secret_key = secret_key
|
||||
|
||||
if result_dict is not None:
|
||||
self.account_id = result_dict['account_id']
|
||||
self.public_key = result_dict['public_key']
|
||||
self.public_key_hex = result_dict['public_key_hex']
|
||||
self.secret_key = result_dict['master_seed']
|
||||
|
||||
# Accounts are equal if they represent the same account on the ledger
|
||||
# I.e. only check the account_id field for equality.
|
||||
def __eq__(self, lhs):
|
||||
if not isinstance(lhs, self.__class__):
|
||||
return False
|
||||
return self.account_id == lhs.account_id
|
||||
|
||||
def __ne__(self, lhs):
|
||||
return not self.__eq__(lhs)
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.nickname is not None:
|
||||
return self.nickname
|
||||
return self.account_id
|
||||
|
||||
def alias_or_account_id(self) -> str:
|
||||
'''
|
||||
return the alias if it exists, otherwise return the id
|
||||
'''
|
||||
if self.nickname is not None:
|
||||
return self.nickname
|
||||
return self.account_id
|
||||
|
||||
def account_id_str_as_hex(self) -> str:
|
||||
return binascii.hexlify(self.account_id.encode()).decode('utf-8')
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
return {
|
||||
'account_id': self.account_id,
|
||||
'nickname': self.nickname,
|
||||
'public_key': self.public_key,
|
||||
'public_key_hex': self.public_key_hex,
|
||||
'secret_key': self.secret_key
|
||||
}
|
||||
|
||||
|
||||
class Asset:
|
||||
'''An XRP or IOU value'''
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
value: Union[int, float, None] = None,
|
||||
currency: Optional[
|
||||
str] = None, # Will default to 'XRP' if not specified
|
||||
issuer: Optional[Account] = None,
|
||||
from_asset=None, # asset is of type Optional[Asset]
|
||||
# from_rpc_result is a python object resulting from an rpc command
|
||||
from_rpc_result: Optional[Union[dict, str]] = None):
|
||||
|
||||
assert from_asset is None or from_rpc_result is None
|
||||
|
||||
self.value = value
|
||||
self.issuer = issuer
|
||||
self.currency = currency
|
||||
if from_asset is not None:
|
||||
if self.value is None:
|
||||
self.value = from_asset.value
|
||||
if self.issuer is None:
|
||||
self.issuer = from_asset.issuer
|
||||
if self.currency is None:
|
||||
self.currency = from_asset.currency
|
||||
if from_rpc_result is not None:
|
||||
if isinstance(from_rpc_result, str):
|
||||
self.value = int(from_rpc_result)
|
||||
self.currency = 'XRP'
|
||||
else:
|
||||
self.value = from_rpc_result['value']
|
||||
self.currency = float(from_rpc_result['currency'])
|
||||
self.issuer = Account(account_id=from_rpc_result['issuer'])
|
||||
|
||||
if self.currency is None:
|
||||
self.currency = 'XRP'
|
||||
|
||||
if isinstance(self.value, str):
|
||||
if self.is_xrp():
|
||||
self.value = int(value)
|
||||
else:
|
||||
self.value = float(value)
|
||||
|
||||
def __call__(self, value: Union[int, float]):
|
||||
'''Call operator useful for a terse syntax for assets in tests. I.e. USD(100)'''
|
||||
return Asset(value=value, from_asset=self)
|
||||
|
||||
def __add__(self, lhs):
|
||||
assert (self.issuer == lhs.issuer and self.currency == lhs.currency)
|
||||
return Asset(value=self.value + lhs.value,
|
||||
currency=self.currency,
|
||||
issuer=self.issuer)
|
||||
|
||||
def __sub__(self, lhs):
|
||||
assert (self.issuer == lhs.issuer and self.currency == lhs.currency)
|
||||
return Asset(value=self.value - lhs.value,
|
||||
currency=self.currency,
|
||||
issuer=self.issuer)
|
||||
|
||||
def __eq__(self, lhs):
|
||||
if not isinstance(lhs, self.__class__):
|
||||
return False
|
||||
return (self.value == lhs.value and self.currency == lhs.currency
|
||||
and self.issuer == lhs.issuer)
|
||||
|
||||
def __ne__(self, lhs):
|
||||
return not self.__eq__(lhs)
|
||||
|
||||
def __str__(self) -> str:
|
||||
value_part = '' if self.value is None else f'{self.value}/'
|
||||
issuer_part = '' if self.issuer is None else f'/{self.issuer}'
|
||||
return f'{value_part}{self.currency}{issuer_part}'
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return self.__str__()
|
||||
|
||||
def is_xrp(self) -> bool:
|
||||
''' return true if the asset represents XRP'''
|
||||
return self.currency == 'XRP'
|
||||
|
||||
def cmd_str(self) -> str:
|
||||
value_part = '' if self.value is None else f'{self.value}/'
|
||||
issuer_part = '' if self.issuer is None else f'/{self.issuer.account_id}'
|
||||
return f'{value_part}{self.currency}{issuer_part}'
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''Return an object suitalbe for use in a command'''
|
||||
if self.currency == 'XRP':
|
||||
if self.value is not None:
|
||||
return f'{self.value}' # must be a string
|
||||
return {'currency': self.currency}
|
||||
result = {'currency': self.currency, 'issuer': self.issuer.account_id}
|
||||
if self.value is not None:
|
||||
result['value'] = f'{self.value}' # must be a string
|
||||
return result
|
||||
|
||||
|
||||
def XRP(v: Union[int, float]) -> Asset:
|
||||
return Asset(value=v * 1_000_000)
|
||||
|
||||
|
||||
def drops(v: int) -> Asset:
|
||||
return Asset(value=v)
|
||||
|
||||
|
||||
class Path:
|
||||
'''Payment Path'''
|
||||
def __init__(self,
|
||||
nodes: Optional[List[Union[Account, Asset]]] = None,
|
||||
*,
|
||||
result_list: Optional[List[dict]] = None):
|
||||
assert not (nodes and result_list)
|
||||
if result_list is not None:
|
||||
self.result_list = result_list
|
||||
return
|
||||
if nodes is None:
|
||||
self.result_list = []
|
||||
return
|
||||
self.result_list = [
|
||||
self._create_account_path_node(n)
|
||||
if isinstance(n, Account) else self._create_currency_path_node(n)
|
||||
for n in nodes
|
||||
]
|
||||
|
||||
def _create_account_path_node(self, account: Account) -> dict:
|
||||
return {
|
||||
'account': account.account_id,
|
||||
'type': 1,
|
||||
'type_hex': '0000000000000001'
|
||||
}
|
||||
|
||||
def _create_currency_path_node(self, asset: Asset) -> dict:
|
||||
result = {
|
||||
'currency': asset.currency,
|
||||
'type': 48,
|
||||
'type_hex': '0000000000000030'
|
||||
}
|
||||
if not asset.is_xrp():
|
||||
result['issuer'] = asset.issuer.account_id
|
||||
return result
|
||||
|
||||
def to_cmd_obj(self) -> list:
|
||||
'''Return an object suitalbe for use in a command'''
|
||||
return self.result_list
|
||||
|
||||
|
||||
class PathList:
|
||||
'''Collection of paths for use in payments'''
|
||||
def __init__(self,
|
||||
path_list: Optional[List[Path]] = None,
|
||||
*,
|
||||
result_list: Optional[List[List[dict]]] = None):
|
||||
# result_list can be the response from the rippled server
|
||||
assert not (path_list and result_list)
|
||||
if result_list is not None:
|
||||
self.paths = [Path(result_list=l) for l in result_list]
|
||||
return
|
||||
self.paths = path_list
|
||||
|
||||
def to_cmd_obj(self) -> list:
|
||||
'''Return an object suitalbe for use in a command'''
|
||||
return [p.to_cmd_obj() for p in self.paths]
|
||||
101
bin/sidechain/python/config_file.py
Normal file
101
bin/sidechain/python/config_file.py
Normal file
@@ -0,0 +1,101 @@
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
|
||||
class Section:
|
||||
def section_header(l: str) -> Optional[str]:
|
||||
'''
|
||||
If the line is a section header, return the section name
|
||||
otherwise return None
|
||||
'''
|
||||
if l.startswith('[') and l.endswith(']'):
|
||||
return l[1:-1]
|
||||
return None
|
||||
|
||||
def __init__(self, name: str):
|
||||
super().__setattr__('_name', name)
|
||||
# lines contains all non key-value pairs
|
||||
super().__setattr__('_lines', [])
|
||||
super().__setattr__('_kv_pairs', {})
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def add_line(self, l):
|
||||
s = l.split('=')
|
||||
if len(s) == 2:
|
||||
self._kv_pairs[s[0].strip()] = s[1].strip()
|
||||
else:
|
||||
self._lines.append(l)
|
||||
|
||||
def get_lines(self):
|
||||
return self._lines
|
||||
|
||||
def get_line(self) -> Optional[str]:
|
||||
if len(self._lines) > 0:
|
||||
return self._lines[0]
|
||||
return None
|
||||
|
||||
def __getattr__(self, name):
|
||||
try:
|
||||
return self._kv_pairs[name]
|
||||
except KeyError:
|
||||
raise AttributeError(name)
|
||||
|
||||
def __setattr__(self, name, value):
|
||||
if name in self.__dict__:
|
||||
super().__setattr__(name, value)
|
||||
else:
|
||||
self._kv_pairs[name] = value
|
||||
|
||||
def __getstate__(self):
|
||||
return vars(self)
|
||||
|
||||
def __setstate__(self, state):
|
||||
vars(self).update(state)
|
||||
|
||||
|
||||
class ConfigFile:
|
||||
def __init__(self, *, file_name: Optional[str] = None):
|
||||
# parse the file
|
||||
self._file_name = file_name
|
||||
self._sections = {}
|
||||
if not file_name:
|
||||
return
|
||||
|
||||
cur_section = None
|
||||
with open(file_name) as f:
|
||||
for n, l in enumerate(f):
|
||||
l = l.strip()
|
||||
if l.startswith('#') or not l:
|
||||
continue
|
||||
if section_name := Section.section_header(l):
|
||||
if cur_section:
|
||||
self.add_section(cur_section)
|
||||
cur_section = Section(section_name)
|
||||
continue
|
||||
if not cur_section:
|
||||
raise ValueError(
|
||||
f'Error parsing config file: {file_name} line_num: {n} line: {l}'
|
||||
)
|
||||
cur_section.add_line(l)
|
||||
|
||||
if cur_section:
|
||||
self.add_section(cur_section)
|
||||
|
||||
def add_section(self, s: Section):
|
||||
self._sections[s.get_name()] = s
|
||||
|
||||
def get_file_name(self):
|
||||
return self._file_name
|
||||
|
||||
def __getstate__(self):
|
||||
return vars(self)
|
||||
|
||||
def __setstate__(self, state):
|
||||
vars(self).update(state)
|
||||
|
||||
def __getattr__(self, name):
|
||||
try:
|
||||
return self._sections[name]
|
||||
except KeyError:
|
||||
raise AttributeError(name)
|
||||
630
bin/sidechain/python/create_config_files.py
Executable file
630
bin/sidechain/python/create_config_files.py
Executable file
@@ -0,0 +1,630 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Generate rippled config files, each with their own ports, database paths, and validation_seeds.
|
||||
# There will be configs for shards/no_shards, main/test nets, two config files for each combination
|
||||
# (so one can run in a dogfood mode while another is tested). To avoid confusion,The directory path
|
||||
# will be $data_dir/{main | test}.{shard | no_shard}.{dog | test}
|
||||
# The config file will reside in that directory with the name rippled.cfg
|
||||
# The validators file will reside in that directory with the name validators.txt
|
||||
'''
|
||||
Script to test and debug sidechains.
|
||||
|
||||
The rippled exe location can be set through the command line or
|
||||
the environment variable RIPPLED_MAINCHAIN_EXE
|
||||
|
||||
The configs_dir (where the config files will reside) can be set through the command line
|
||||
or the environment variable RIPPLED_SIDECHAIN_CFG_DIR
|
||||
'''
|
||||
|
||||
import argparse
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Dict, List, Optional, Tuple, Union
|
||||
|
||||
from config_file import ConfigFile
|
||||
from command import ValidationCreate, WalletPropose
|
||||
from common import Account, Asset, eprint, XRP
|
||||
from app import App, single_client_app
|
||||
|
||||
mainnet_validators = """
|
||||
[validator_list_sites]
|
||||
https://vl.ripple.com
|
||||
|
||||
[validator_list_keys]
|
||||
ED2677ABFFD1B33AC6FBC3062B71F1E8397C1505E1C42C64D11AD1B28FF73F4734
|
||||
"""
|
||||
|
||||
altnet_validators = """
|
||||
[validator_list_sites]
|
||||
https://vl.altnet.rippletest.net
|
||||
|
||||
[validator_list_keys]
|
||||
ED264807102805220DA0F312E71FC2C69E1552C9C5790F6C25E3729DEB573D5860
|
||||
"""
|
||||
|
||||
node_size = 'medium'
|
||||
default_data_dir = '/home/swd/data/rippled'
|
||||
|
||||
|
||||
@dataclass
|
||||
class Keypair:
|
||||
public_key: str
|
||||
secret_key: str
|
||||
account_id: Optional[str]
|
||||
|
||||
|
||||
def generate_node_keypairs(n: int, rip: App) -> List[Keypair]:
|
||||
'''
|
||||
generate keypairs suitable for validator keys
|
||||
'''
|
||||
result = []
|
||||
for i in range(n):
|
||||
keys = rip(ValidationCreate())
|
||||
result.append(
|
||||
Keypair(public_key=keys["validation_public_key"],
|
||||
secret_key=keys["validation_seed"],
|
||||
account_id=None))
|
||||
return result
|
||||
|
||||
|
||||
def generate_federator_keypairs(n: int, rip: App) -> List[Keypair]:
|
||||
'''
|
||||
generate keypairs suitable for federator keys
|
||||
'''
|
||||
result = []
|
||||
for i in range(n):
|
||||
keys = rip(WalletPropose(key_type='ed25519'))
|
||||
result.append(
|
||||
Keypair(public_key=keys["public_key"],
|
||||
secret_key=keys["master_seed"],
|
||||
account_id=keys["account_id"]))
|
||||
return result
|
||||
|
||||
|
||||
class Ports:
|
||||
'''
|
||||
Port numbers for various services.
|
||||
Port numbers differ by cfg_index so different configs can run
|
||||
at the same time without interfering with each other.
|
||||
'''
|
||||
peer_port_base = 51235
|
||||
http_admin_port_base = 5005
|
||||
ws_public_port_base = 6005
|
||||
|
||||
def __init__(self, cfg_index: int):
|
||||
self.peer_port = Ports.peer_port_base + cfg_index
|
||||
self.http_admin_port = Ports.http_admin_port_base + cfg_index
|
||||
self.ws_public_port = Ports.ws_public_port_base + (2 * cfg_index)
|
||||
# note admin port uses public port base
|
||||
self.ws_admin_port = Ports.ws_public_port_base + (2 * cfg_index) + 1
|
||||
|
||||
|
||||
class Network:
|
||||
def __init__(self, num_nodes: int, num_validators: int,
|
||||
start_cfg_index: int, rip: App):
|
||||
self.validator_keypairs = generate_node_keypairs(num_validators, rip)
|
||||
self.ports = [Ports(start_cfg_index + i) for i in range(num_nodes)]
|
||||
|
||||
|
||||
class SidechainNetwork(Network):
|
||||
def __init__(self, num_nodes: int, num_federators: int,
|
||||
num_validators: int, start_cfg_index: int, rip: App):
|
||||
super().__init__(num_nodes, num_validators, start_cfg_index, rip)
|
||||
self.federator_keypairs = generate_federator_keypairs(
|
||||
num_federators, rip)
|
||||
self.main_account = rip(WalletPropose(key_type='secp256k1'))
|
||||
|
||||
|
||||
class XChainAsset:
|
||||
def __init__(self, main_asset: Asset, side_asset: Asset,
|
||||
main_value: Union[int, float], side_value: Union[int, float],
|
||||
main_refund_penalty: Union[int, float],
|
||||
side_refund_penalty: Union[int, float]):
|
||||
self.main_asset = main_asset(main_value)
|
||||
self.side_asset = side_asset(side_value)
|
||||
self.main_refund_penalty = main_asset(main_refund_penalty)
|
||||
self.side_refund_penalty = side_asset(side_refund_penalty)
|
||||
|
||||
|
||||
def generate_asset_stanzas(
|
||||
assets: Optional[Dict[str, XChainAsset]] = None) -> str:
|
||||
if assets is None:
|
||||
# default to xrp only at a 1:1 value
|
||||
assets = {}
|
||||
assets['xrp_xrp_sidechain_asset'] = XChainAsset(
|
||||
XRP(0), XRP(0), 1, 1, 400, 400)
|
||||
|
||||
index_stanza = """
|
||||
[sidechain_assets]"""
|
||||
|
||||
asset_stanzas = []
|
||||
|
||||
for name, xchainasset in assets.items():
|
||||
index_stanza += '\n' + name
|
||||
new_stanza = f"""
|
||||
[{name}]
|
||||
mainchain_asset={json.dumps(xchainasset.main_asset.to_cmd_obj())}
|
||||
sidechain_asset={json.dumps(xchainasset.side_asset.to_cmd_obj())}
|
||||
mainchain_refund_penalty={json.dumps(xchainasset.main_refund_penalty.to_cmd_obj())}
|
||||
sidechain_refund_penalty={json.dumps(xchainasset.side_refund_penalty.to_cmd_obj())}"""
|
||||
asset_stanzas.append(new_stanza)
|
||||
|
||||
return index_stanza + '\n' + '\n'.join(asset_stanzas)
|
||||
|
||||
|
||||
# First element of the returned tuple is the sidechain stanzas
|
||||
# second element is the bootstrap stanzas
|
||||
def generate_sidechain_stanza(
|
||||
mainchain_ports: Ports,
|
||||
main_account: dict,
|
||||
federators: List[Keypair],
|
||||
signing_key: str,
|
||||
mainchain_cfg_file: str,
|
||||
xchain_assets: Optional[Dict[str,
|
||||
XChainAsset]] = None) -> Tuple[str, str]:
|
||||
mainchain_ip = "127.0.0.1"
|
||||
|
||||
federators_stanza = """
|
||||
# federator signing public keys
|
||||
[sidechain_federators]
|
||||
"""
|
||||
federators_secrets_stanza = """
|
||||
# federator signing secret keys (for standalone-mode testing only; Normally won't be in a config file)
|
||||
[sidechain_federators_secrets]
|
||||
"""
|
||||
bootstrap_federators_stanza = """
|
||||
# first value is federator signing public key, second is the signing pk account
|
||||
[sidechain_federators]
|
||||
"""
|
||||
|
||||
assets_stanzas = generate_asset_stanzas(xchain_assets)
|
||||
|
||||
for fed in federators:
|
||||
federators_stanza += f'{fed.public_key}\n'
|
||||
federators_secrets_stanza += f'{fed.secret_key}\n'
|
||||
bootstrap_federators_stanza += f'{fed.public_key} {fed.account_id}\n'
|
||||
|
||||
sidechain_stanzas = f"""
|
||||
[sidechain]
|
||||
signing_key={signing_key}
|
||||
mainchain_account={main_account["account_id"]}
|
||||
mainchain_ip={mainchain_ip}
|
||||
mainchain_port_ws={mainchain_ports.ws_public_port}
|
||||
# mainchain config file is: {mainchain_cfg_file}
|
||||
|
||||
{assets_stanzas}
|
||||
|
||||
{federators_stanza}
|
||||
|
||||
{federators_secrets_stanza}
|
||||
"""
|
||||
bootstrap_stanzas = f"""
|
||||
[sidechain]
|
||||
mainchain_secret={main_account["master_seed"]}
|
||||
|
||||
{bootstrap_federators_stanza}
|
||||
"""
|
||||
return (sidechain_stanzas, bootstrap_stanzas)
|
||||
|
||||
|
||||
# cfg_type will typically be either 'dog' or 'test', but can be any string. It is only used
|
||||
# to create the data directories.
|
||||
def generate_cfg_dir(*,
|
||||
ports: Ports,
|
||||
with_shards: bool,
|
||||
main_net: bool,
|
||||
cfg_type: str,
|
||||
sidechain_stanza: str,
|
||||
sidechain_bootstrap_stanza: str,
|
||||
validation_seed: Optional[str] = None,
|
||||
validators: Optional[List[str]] = None,
|
||||
fixed_ips: Optional[List[Ports]] = None,
|
||||
data_dir: str,
|
||||
full_history: bool = False,
|
||||
with_hooks: bool = False) -> str:
|
||||
ips_stanza = ''
|
||||
this_ip = '127.0.0.1'
|
||||
if fixed_ips:
|
||||
ips_stanza = '# Fixed ips for a testnet.\n'
|
||||
ips_stanza += '[ips_fixed]\n'
|
||||
for i, p in enumerate(fixed_ips):
|
||||
if p.peer_port == ports.peer_port:
|
||||
continue
|
||||
# rippled limits the number of connects per ip. So use the other loopback devices
|
||||
ips_stanza += f'127.0.0.{i+1} {p.peer_port}\n'
|
||||
else:
|
||||
ips_stanza = '# Where to find some other servers speaking the Ripple protocol.\n'
|
||||
ips_stanza += '[ips]\n'
|
||||
if main_net:
|
||||
ips_stanza += 'r.ripple.com 51235\n'
|
||||
else:
|
||||
ips_stanza += 'r.altnet.rippletest.net 51235\n'
|
||||
disable_shards = '' if with_shards else '# '
|
||||
disable_delete = '#' if full_history else ''
|
||||
history_line = 'full' if full_history else '256'
|
||||
earliest_seq_line = ''
|
||||
if sidechain_stanza:
|
||||
earliest_seq_line = 'earliest_seq=1'
|
||||
hooks_line = 'Hooks' if with_hooks else ''
|
||||
validation_seed_stanza = ''
|
||||
if validation_seed:
|
||||
validation_seed_stanza = f'''
|
||||
[validation_seed]
|
||||
{validation_seed}
|
||||
'''
|
||||
node_size = 'medium'
|
||||
shard_str = 'shards' if with_shards else 'no_shards'
|
||||
net_str = 'main' if main_net else 'test'
|
||||
if not fixed_ips:
|
||||
sub_dir = data_dir + f'/{net_str}.{shard_str}.{cfg_type}'
|
||||
if sidechain_stanza:
|
||||
sub_dir += '.sidechain'
|
||||
else:
|
||||
sub_dir = data_dir + f'/{cfg_type}'
|
||||
db_path = sub_dir + '/db'
|
||||
debug_logfile = sub_dir + '/debug.log'
|
||||
shard_db_path = sub_dir + '/shards'
|
||||
node_db_path = db_path + '/nudb'
|
||||
|
||||
cfg_str = f"""
|
||||
[server]
|
||||
port_rpc_admin_local
|
||||
port_peer
|
||||
port_ws_admin_local
|
||||
port_ws_public
|
||||
#ssl_key = /etc/ssl/private/server.key
|
||||
#ssl_cert = /etc/ssl/certs/server.crt
|
||||
|
||||
[port_rpc_admin_local]
|
||||
port = {ports.http_admin_port}
|
||||
ip = {this_ip}
|
||||
admin = {this_ip}
|
||||
protocol = http
|
||||
|
||||
[port_peer]
|
||||
port = {ports.peer_port}
|
||||
ip = 0.0.0.0
|
||||
protocol = peer
|
||||
|
||||
[port_ws_admin_local]
|
||||
port = {ports.ws_admin_port}
|
||||
ip = {this_ip}
|
||||
admin = {this_ip}
|
||||
protocol = ws
|
||||
|
||||
[port_ws_public]
|
||||
port = {ports.ws_public_port}
|
||||
ip = {this_ip}
|
||||
protocol = ws
|
||||
# protocol = wss
|
||||
|
||||
[node_size]
|
||||
{node_size}
|
||||
|
||||
[ledger_history]
|
||||
{history_line}
|
||||
|
||||
[node_db]
|
||||
type=NuDB
|
||||
path={node_db_path}
|
||||
open_files=2000
|
||||
filter_bits=12
|
||||
cache_mb=256
|
||||
file_size_mb=8
|
||||
file_size_mult=2
|
||||
{earliest_seq_line}
|
||||
{disable_delete}online_delete=256
|
||||
{disable_delete}advisory_delete=0
|
||||
|
||||
[database_path]
|
||||
{db_path}
|
||||
|
||||
# This needs to be an absolute directory reference, not a relative one.
|
||||
# Modify this value as required.
|
||||
[debug_logfile]
|
||||
{debug_logfile}
|
||||
|
||||
[sntp_servers]
|
||||
time.windows.com
|
||||
time.apple.com
|
||||
time.nist.gov
|
||||
pool.ntp.org
|
||||
|
||||
{ips_stanza}
|
||||
|
||||
[validators_file]
|
||||
validators.txt
|
||||
|
||||
[rpc_startup]
|
||||
{{ "command": "log_level", "severity": "fatal" }}
|
||||
{{ "command": "log_level", "partition": "SidechainFederator", "severity": "trace" }}
|
||||
|
||||
[ssl_verify]
|
||||
1
|
||||
|
||||
{validation_seed_stanza}
|
||||
|
||||
{disable_shards}[shard_db]
|
||||
{disable_shards}type=NuDB
|
||||
{disable_shards}path={shard_db_path}
|
||||
{disable_shards}max_historical_shards=6
|
||||
|
||||
{sidechain_stanza}
|
||||
|
||||
[features]
|
||||
{hooks_line}
|
||||
PayChan
|
||||
Flow
|
||||
FlowCross
|
||||
TickSize
|
||||
fix1368
|
||||
Escrow
|
||||
fix1373
|
||||
EnforceInvariants
|
||||
SortedDirectories
|
||||
fix1201
|
||||
fix1512
|
||||
fix1513
|
||||
fix1523
|
||||
fix1528
|
||||
DepositAuth
|
||||
Checks
|
||||
fix1571
|
||||
fix1543
|
||||
fix1623
|
||||
DepositPreauth
|
||||
fix1515
|
||||
fix1578
|
||||
MultiSignReserve
|
||||
fixTakerDryOfferRemoval
|
||||
fixMasterKeyAsRegularKey
|
||||
fixCheckThreading
|
||||
fixPayChanRecipientOwnerDir
|
||||
DeletableAccounts
|
||||
fixQualityUpperBound
|
||||
RequireFullyCanonicalSig
|
||||
fix1781
|
||||
HardenedValidations
|
||||
fixAmendmentMajorityCalc
|
||||
NegativeUNL
|
||||
TicketBatch
|
||||
FlowSortStrands
|
||||
fixSTAmountCanonicalize
|
||||
fixRmSmallIncreasedQOffers
|
||||
CheckCashMakesTrustLine
|
||||
"""
|
||||
|
||||
validators_str = ''
|
||||
for p in [sub_dir, db_path, shard_db_path]:
|
||||
Path(p).mkdir(parents=True, exist_ok=True)
|
||||
# Add the validators.txt file
|
||||
if validators:
|
||||
validators_str = '[validators]\n'
|
||||
for k in validators:
|
||||
validators_str += f'{k}\n'
|
||||
else:
|
||||
validators_str = mainnet_validators if main_net else altnet_validators
|
||||
with open(sub_dir + "/validators.txt", "w") as f:
|
||||
f.write(validators_str)
|
||||
|
||||
# add the rippled.cfg file
|
||||
with open(sub_dir + "/rippled.cfg", "w") as f:
|
||||
f.write(cfg_str)
|
||||
|
||||
if sidechain_bootstrap_stanza:
|
||||
# add the bootstrap file
|
||||
with open(sub_dir + "/sidechain_bootstrap.cfg", "w") as f:
|
||||
f.write(sidechain_bootstrap_stanza)
|
||||
|
||||
return sub_dir + "/rippled.cfg"
|
||||
|
||||
|
||||
def generate_multinode_net(out_dir: str,
|
||||
mainnet: Network,
|
||||
sidenet: SidechainNetwork,
|
||||
xchain_assets: Optional[Dict[str,
|
||||
XChainAsset]] = None):
|
||||
mainnet_cfgs = []
|
||||
for i in range(len(mainnet.ports)):
|
||||
validator_kp = mainnet.validator_keypairs[i]
|
||||
ports = mainnet.ports[i]
|
||||
mainchain_cfg_file = generate_cfg_dir(
|
||||
ports=ports,
|
||||
with_shards=False,
|
||||
main_net=True,
|
||||
cfg_type=f'mainchain_{i}',
|
||||
sidechain_stanza='',
|
||||
sidechain_bootstrap_stanza='',
|
||||
validation_seed=validator_kp.secret_key,
|
||||
data_dir=out_dir)
|
||||
mainnet_cfgs.append(mainchain_cfg_file)
|
||||
|
||||
for i in range(len(sidenet.ports)):
|
||||
validator_kp = sidenet.validator_keypairs[i]
|
||||
ports = sidenet.ports[i]
|
||||
|
||||
mainnet_i = i % len(mainnet.ports)
|
||||
sidechain_stanza, sidechain_bootstrap_stanza = generate_sidechain_stanza(
|
||||
mainnet.ports[mainnet_i], sidenet.main_account,
|
||||
sidenet.federator_keypairs,
|
||||
sidenet.federator_keypairs[i].secret_key, mainnet_cfgs[mainnet_i],
|
||||
xchain_assets)
|
||||
|
||||
generate_cfg_dir(
|
||||
ports=ports,
|
||||
with_shards=False,
|
||||
main_net=True,
|
||||
cfg_type=f'sidechain_{i}',
|
||||
sidechain_stanza=sidechain_stanza,
|
||||
sidechain_bootstrap_stanza=sidechain_bootstrap_stanza,
|
||||
validation_seed=validator_kp.secret_key,
|
||||
validators=[kp.public_key for kp in sidenet.validator_keypairs],
|
||||
fixed_ips=sidenet.ports,
|
||||
data_dir=out_dir,
|
||||
full_history=True,
|
||||
with_hooks=False)
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description=('Create config files for testing sidechains'))
|
||||
|
||||
parser.add_argument(
|
||||
'--exe',
|
||||
'-e',
|
||||
help=('path to rippled executable'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--usd',
|
||||
'-u',
|
||||
action='store_true',
|
||||
help=('include a USD/root IOU asset for cross chain transfers'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--cfgs_dir',
|
||||
'-c',
|
||||
help=
|
||||
('path to configuration file dir (where the output config files will be located)'
|
||||
),
|
||||
)
|
||||
|
||||
return parser.parse_known_args()[0]
|
||||
|
||||
|
||||
class Params:
|
||||
def __init__(self):
|
||||
args = parse_args()
|
||||
|
||||
self.exe = None
|
||||
if 'RIPPLED_MAINCHAIN_EXE' in os.environ:
|
||||
self.exe = os.environ['RIPPLED_MAINCHAIN_EXE']
|
||||
if args.exe:
|
||||
self.exe = args.exe
|
||||
|
||||
self.configs_dir = None
|
||||
if 'RIPPLED_SIDECHAIN_CFG_DIR' in os.environ:
|
||||
self.configs_dir = os.environ['RIPPLED_SIDECHAIN_CFG_DIR']
|
||||
if args.cfgs_dir:
|
||||
self.configs_dir = args.cfgs_dir
|
||||
|
||||
self.usd = False
|
||||
if args.usd:
|
||||
self.usd = args.usd
|
||||
|
||||
def check_error(self) -> str:
|
||||
'''
|
||||
Check for errors. Return `None` if no errors,
|
||||
otherwise return a string describing the error
|
||||
'''
|
||||
if not self.exe:
|
||||
return 'Missing exe location. Either set the env variable RIPPLED_MAINCHAIN_EXE or use the --exe_mainchain command line switch'
|
||||
if not self.configs_dir:
|
||||
return 'Missing configs directory location. Either set the env variable RIPPLED_SIDECHAIN_CFG_DIR or use the --cfgs_dir command line switch'
|
||||
|
||||
|
||||
def main(params: Params,
|
||||
xchain_assets: Optional[Dict[str, XChainAsset]] = None):
|
||||
|
||||
if err_str := params.check_error():
|
||||
eprint(err_str)
|
||||
sys.exit(1)
|
||||
index = 0
|
||||
nonvalidator_cfg_file_name = generate_cfg_dir(
|
||||
ports=Ports(index),
|
||||
with_shards=False,
|
||||
main_net=True,
|
||||
cfg_type='non_validator',
|
||||
sidechain_stanza='',
|
||||
sidechain_bootstrap_stanza='',
|
||||
validation_seed=None,
|
||||
data_dir=params.configs_dir)
|
||||
index = index + 1
|
||||
|
||||
nonvalidator_config = ConfigFile(file_name=nonvalidator_cfg_file_name)
|
||||
with single_client_app(exe=params.exe,
|
||||
config=nonvalidator_config,
|
||||
standalone=True) as rip:
|
||||
mainnet = Network(num_nodes=1,
|
||||
num_validators=1,
|
||||
start_cfg_index=index,
|
||||
rip=rip)
|
||||
sidenet = SidechainNetwork(num_nodes=5,
|
||||
num_federators=5,
|
||||
num_validators=5,
|
||||
start_cfg_index=index + 1,
|
||||
rip=rip)
|
||||
generate_multinode_net(
|
||||
out_dir=f'{params.configs_dir}/sidechain_testnet',
|
||||
mainnet=mainnet,
|
||||
sidenet=sidenet,
|
||||
xchain_assets=xchain_assets)
|
||||
index = index + 2
|
||||
|
||||
(Path(params.configs_dir) / 'logs').mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for with_shards in [True, False]:
|
||||
for is_main_net in [True, False]:
|
||||
for cfg_type in ['dog', 'test', 'one', 'two']:
|
||||
if not is_main_net and cfg_type not in ['dog', 'test']:
|
||||
continue
|
||||
|
||||
mainnet = Network(num_nodes=1,
|
||||
num_validators=1,
|
||||
start_cfg_index=index,
|
||||
rip=rip)
|
||||
mainchain_cfg_file = generate_cfg_dir(
|
||||
data_dir=params.configs_dir,
|
||||
ports=mainnet.ports[0],
|
||||
with_shards=with_shards,
|
||||
main_net=is_main_net,
|
||||
cfg_type=cfg_type,
|
||||
sidechain_stanza='',
|
||||
sidechain_bootstrap_stanza='',
|
||||
validation_seed=mainnet.validator_keypairs[0].
|
||||
secret_key)
|
||||
|
||||
sidenet = SidechainNetwork(num_nodes=1,
|
||||
num_federators=5,
|
||||
num_validators=1,
|
||||
start_cfg_index=index + 1,
|
||||
rip=rip)
|
||||
signing_key = sidenet.federator_keypairs[0].secret_key
|
||||
|
||||
sidechain_stanza, sizechain_bootstrap_stanza = generate_sidechain_stanza(
|
||||
mainnet.ports[0], sidenet.main_account,
|
||||
sidenet.federator_keypairs, signing_key,
|
||||
mainchain_cfg_file, xchain_assets)
|
||||
|
||||
generate_cfg_dir(
|
||||
data_dir=params.configs_dir,
|
||||
ports=sidenet.ports[0],
|
||||
with_shards=with_shards,
|
||||
main_net=is_main_net,
|
||||
cfg_type=cfg_type,
|
||||
sidechain_stanza=sidechain_stanza,
|
||||
sidechain_bootstrap_stanza=sizechain_bootstrap_stanza,
|
||||
validation_seed=sidenet.validator_keypairs[0].
|
||||
secret_key)
|
||||
index = index + 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
params = Params()
|
||||
|
||||
xchain_assets = None
|
||||
if params.usd:
|
||||
xchain_assets = {}
|
||||
xchain_assets['xrp_xrp_sidechain_asset'] = XChainAsset(
|
||||
XRP(0), XRP(0), 1, 1, 200, 200)
|
||||
root_account = Account(account_id="rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")
|
||||
main_iou_asset = Asset(value=0, currency='USD', issuer=root_account)
|
||||
side_iou_asset = Asset(value=0, currency='USD', issuer=root_account)
|
||||
xchain_assets['iou_iou_sidechain_asset'] = XChainAsset(
|
||||
main_iou_asset, side_iou_asset, 1, 1, 0.02, 0.02)
|
||||
|
||||
main(params, xchain_assets)
|
||||
1496
bin/sidechain/python/interactive.py
Normal file
1496
bin/sidechain/python/interactive.py
Normal file
File diff suppressed because it is too large
Load Diff
198
bin/sidechain/python/log_analyzer.py
Executable file
198
bin/sidechain/python/log_analyzer.py
Executable file
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
from common import eprint
|
||||
from typing import IO, Optional
|
||||
|
||||
|
||||
class LogLine:
|
||||
UNSTRUCTURED_RE = re.compile(r'''(?x)
|
||||
# The x flag enables insignificant whitespace mode (allowing comments)
|
||||
^(?P<timestamp>.*UTC)
|
||||
[\ ]
|
||||
(?P<module>[^:]*):(?P<level>[^\ ]*)
|
||||
[\ ]
|
||||
(?P<msg>.*$)
|
||||
''')
|
||||
|
||||
STRUCTURED_RE = re.compile(r'''(?x)
|
||||
# The x flag enables insignificant whitespace mode (allowing comments)
|
||||
^(?P<timestamp>.*UTC)
|
||||
[\ ]
|
||||
(?P<module>[^:]*):(?P<level>[^\ ]*)
|
||||
[\ ]
|
||||
(?P<msg>[^{]*)
|
||||
[\ ]
|
||||
(?P<json_data>.*$)
|
||||
''')
|
||||
|
||||
def __init__(self, line: str):
|
||||
self.raw_line = line
|
||||
self.json_data = None
|
||||
|
||||
try:
|
||||
if line.endswith('}'):
|
||||
m = self.STRUCTURED_RE.match(line)
|
||||
try:
|
||||
self.json_data = json.loads(m.group('json_data'))
|
||||
except:
|
||||
m = self.UNSTRUCTURED_RE.match(line)
|
||||
else:
|
||||
m = self.UNSTRUCTURED_RE.match(line)
|
||||
|
||||
self.timestamp = m.group('timestamp')
|
||||
self.level = m.group('level')
|
||||
self.module = m.group('module')
|
||||
self.msg = m.group('msg')
|
||||
except Exception as e:
|
||||
eprint(f'init exception: {e} line: {line}')
|
||||
|
||||
def to_mixed_json_str(self) -> str:
|
||||
'''
|
||||
return a pretty printed string as mixed json
|
||||
'''
|
||||
try:
|
||||
r = f'{self.timestamp} {self.module}:{self.level} {self.msg}'
|
||||
if self.json_data:
|
||||
r += '\n' + json.dumps(self.json_data, indent=1)
|
||||
return r
|
||||
except:
|
||||
eprint(f'Using raw line: {self.raw_line}')
|
||||
return self.raw_line
|
||||
|
||||
def to_pure_json(self) -> dict:
|
||||
'''
|
||||
return a json dict
|
||||
'''
|
||||
dict = {}
|
||||
dict['t'] = self.timestamp
|
||||
dict['m'] = self.module
|
||||
dict['l'] = self.level
|
||||
dict['msg'] = self.msg
|
||||
if self.json_data:
|
||||
dict['data'] = self.json_data
|
||||
return dict
|
||||
|
||||
def to_pure_json_str(self, f_id: Optional[str] = None) -> str:
|
||||
'''
|
||||
return a pretty printed string as pure json
|
||||
'''
|
||||
try:
|
||||
dict = self.to_pure_json(f_id)
|
||||
return json.dumps(dict, indent=1)
|
||||
except:
|
||||
return self.raw_line
|
||||
|
||||
|
||||
def convert_log(in_file_name: str,
|
||||
out: str,
|
||||
*,
|
||||
as_list=False,
|
||||
pure_json=False,
|
||||
module: Optional[str] = 'SidechainFederator') -> list:
|
||||
result = []
|
||||
try:
|
||||
prev_lines = None
|
||||
with open(in_file_name) as input:
|
||||
for l in input:
|
||||
l = l.strip()
|
||||
if not l:
|
||||
continue
|
||||
if LogLine.UNSTRUCTURED_RE.match(l):
|
||||
if prev_lines:
|
||||
log_line = LogLine(prev_lines)
|
||||
if not module or log_line.module == module:
|
||||
if as_list:
|
||||
result.append(log_line.to_pure_json())
|
||||
else:
|
||||
if pure_json:
|
||||
print(log_line.to_pure_json_str(),
|
||||
file=out)
|
||||
else:
|
||||
print(log_line.to_mixed_json_str(),
|
||||
file=out)
|
||||
prev_lines = l
|
||||
else:
|
||||
if not prev_lines:
|
||||
eprint(f'Error: Expected prev_lines. Cur line: {l}')
|
||||
assert prev_lines
|
||||
prev_lines += f' {l}'
|
||||
if prev_lines:
|
||||
log_line = LogLine(prev_lines)
|
||||
if not module or log_line.module == module:
|
||||
if as_list:
|
||||
result.append(log_line.to_pure_json())
|
||||
else:
|
||||
if pure_json:
|
||||
print(log_line.to_pure_json_str(f_id),
|
||||
file=out,
|
||||
flush=True)
|
||||
else:
|
||||
print(log_line.to_mixed_json_str(),
|
||||
file=out,
|
||||
flush=True)
|
||||
except Exception as e:
|
||||
eprint(f'Excption: {e}')
|
||||
raise e
|
||||
return result
|
||||
|
||||
|
||||
def convert_all(in_dir_name: str, out: IO, *, pure_json=False):
|
||||
'''
|
||||
Convert all the "debug.log" log files in one directory level below the in_dir_name into a single json file.
|
||||
There will be a field called 'f' for the director name that the origional log file came from.
|
||||
This is useful when analyzing networks that run on the local machine.
|
||||
'''
|
||||
if not os.path.isdir(in_dir_name):
|
||||
print(f'Error: {in_dir_name} is not a directory')
|
||||
files = []
|
||||
f_ids = []
|
||||
for subdir in os.listdir(in_dir_name):
|
||||
file = f'{in_dir_name}/{subdir}/debug.log'
|
||||
if not os.path.isfile(file):
|
||||
continue
|
||||
files.append(file)
|
||||
f_ids.append(subdir)
|
||||
|
||||
result = {}
|
||||
for f, f_id in zip(files, f_ids):
|
||||
l = convert_log(f, out, as_list=True, pure_json=pure_json, module=None)
|
||||
result[f_id] = l
|
||||
print(json.dumps(result, indent=1), file=out, flush=True)
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description=('python script to convert log files to json'))
|
||||
|
||||
parser.add_argument(
|
||||
'--input',
|
||||
'-i',
|
||||
help=('input log file or sidechain config directory structure'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--output',
|
||||
'-o',
|
||||
help=('output log file'),
|
||||
)
|
||||
|
||||
return parser.parse_known_args()[0]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
args = parse_args()
|
||||
with open(args.output, "w") as out:
|
||||
if os.path.isdir(args.input):
|
||||
convert_all(args.input, out, pure_json=True)
|
||||
else:
|
||||
convert_log(args.input, out, pure_json=True)
|
||||
except Exception as e:
|
||||
eprint(f'Excption: {e}')
|
||||
raise e
|
||||
285
bin/sidechain/python/log_report.py
Executable file
285
bin/sidechain/python/log_report.py
Executable file
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
from collections import defaultdict
|
||||
import datetime
|
||||
import json
|
||||
import numpy as np
|
||||
import os
|
||||
import pandas as pd
|
||||
import string
|
||||
import sys
|
||||
from typing import Dict, Set
|
||||
|
||||
from common import eprint
|
||||
import log_analyzer
|
||||
|
||||
|
||||
def _has_256bit_hex_field_other(data, result: Set[str]):
|
||||
return
|
||||
|
||||
|
||||
_has_256bit_hex_field_overloads = defaultdict(
|
||||
lambda: _has_256bit_hex_field_other)
|
||||
|
||||
|
||||
def _has_256bit_hex_field_str(data: str, result: Set[str]):
|
||||
if len(data) != 64:
|
||||
return
|
||||
for c in data:
|
||||
o = ord(c.upper())
|
||||
if ord('A') <= o <= ord('F'):
|
||||
continue
|
||||
if ord('0') <= o <= ord('9'):
|
||||
continue
|
||||
return
|
||||
result.add(data)
|
||||
|
||||
|
||||
_has_256bit_hex_field_overloads[str] = _has_256bit_hex_field_str
|
||||
|
||||
|
||||
def _has_256bit_hex_field_dict(data: dict, result: Set[str]):
|
||||
for k, v in data.items():
|
||||
if k in [
|
||||
"meta", "index", "LedgerIndex", "ledger_index", "ledger_hash",
|
||||
"SigningPubKey", "suppression"
|
||||
]:
|
||||
continue
|
||||
_has_256bit_hex_field_overloads[type(v)](v, result)
|
||||
|
||||
|
||||
_has_256bit_hex_field_overloads[dict] = _has_256bit_hex_field_dict
|
||||
|
||||
|
||||
def _has_256bit_hex_field_list(data: list, result: Set[str]):
|
||||
for v in data:
|
||||
_has_256bit_hex_field_overloads[type(v)](v, result)
|
||||
|
||||
|
||||
_has_256bit_hex_field_overloads[list] = _has_256bit_hex_field_list
|
||||
|
||||
|
||||
def has_256bit_hex_field(data: dict) -> Set[str]:
|
||||
'''
|
||||
Find all the fields that are strings 64 chars long with only hex digits
|
||||
This is useful when grouping transactions by hex
|
||||
'''
|
||||
result = set()
|
||||
_has_256bit_hex_field_dict(data, result)
|
||||
return result
|
||||
|
||||
|
||||
def group_by_txn(data: dict) -> dict:
|
||||
'''
|
||||
return a dictionary where the key is the transaction hash, the value is another dictionary.
|
||||
The second dictionary the key is the server id, and the values are a list of log items
|
||||
'''
|
||||
def _make_default():
|
||||
return defaultdict(lambda: list())
|
||||
|
||||
result = defaultdict(_make_default)
|
||||
for server_id, log_list in data.items():
|
||||
for log_item in log_list:
|
||||
if txn_hashes := has_256bit_hex_field(log_item):
|
||||
for h in txn_hashes:
|
||||
result[h][server_id].append(log_item)
|
||||
return result
|
||||
|
||||
|
||||
def _rekey_dict_by_txn_date(hash_to_timestamp: dict,
|
||||
grouped_by_txn: dict) -> dict:
|
||||
'''
|
||||
hash_to_timestamp is a dictionary with a key of the txn hash and a value of the timestamp.
|
||||
grouped_by_txn is a dictionary with a key of the txn and an unspecified value.
|
||||
the keys in hash_to_timestamp are a superset of the keys in grouped_by_txn
|
||||
This function returns a new grouped_by_txn dictionary with the transactions sorted by date.
|
||||
'''
|
||||
known_txns = [
|
||||
k for k, v in sorted(hash_to_timestamp.items(), key=lambda x: x[1])
|
||||
]
|
||||
result = {}
|
||||
for k, v in grouped_by_txn.items():
|
||||
if k not in known_txns:
|
||||
result[k] = v
|
||||
for h in known_txns:
|
||||
result[h] = grouped_by_txn[h]
|
||||
return result
|
||||
|
||||
|
||||
def _to_timestamp(str_time: str) -> datetime.datetime:
|
||||
return datetime.datetime.strptime(
|
||||
str_time.split('.')[0], "%Y-%b-%d %H:%M:%S")
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self, in_dir, out_dir):
|
||||
self.in_dir = in_dir
|
||||
self.out_dir = out_dir
|
||||
|
||||
self.combined_logs_file_name = f'{self.out_dir}/combined_logs.json'
|
||||
self.grouped_by_txn_file_name = f'{self.out_dir}/grouped_by_txn.json'
|
||||
self.counts_by_txn_and_server_file_name = f'{self.out_dir}/counts_by_txn_and_server.org'
|
||||
self.data = None # combined logs
|
||||
|
||||
# grouped_by_txn is a dictionary where the key is the server id. mainchain servers
|
||||
# have a key of `mainchain_#` and sidechain servers have a key of
|
||||
# `sidechain_#`, where `#` is a number.
|
||||
self.grouped_by_txn = None
|
||||
|
||||
if not os.path.isdir(in_dir):
|
||||
eprint(f'The input {self.in_dir} must be an existing directory')
|
||||
sys.exit(1)
|
||||
|
||||
if os.path.exists(self.out_dir):
|
||||
if not os.path.isdir(self.out_dir):
|
||||
eprint(
|
||||
f'The output: {self.out_dir} exists and is not a directory'
|
||||
)
|
||||
sys.exit(1)
|
||||
else:
|
||||
os.makedirs(self.out_dir)
|
||||
|
||||
self.combine_logs()
|
||||
with open(self.combined_logs_file_name) as f:
|
||||
self.data = json.load(f)
|
||||
self.grouped_by_txn = group_by_txn(self.data)
|
||||
|
||||
# counts_by_txn_and_server is a dictionary where the key is the txn_hash
|
||||
# and the value is a pandas df with a row for every server and a column for every message
|
||||
# the value is a count of how many times that message appears for that server.
|
||||
counts_by_txn_and_server = {}
|
||||
# dict where the key is a transaction hash and the value is the transaction
|
||||
hash_to_txn = {}
|
||||
# dict where the key is a transaction hash and the value is earliest timestamp in a log file
|
||||
hash_to_timestamp = {}
|
||||
for txn_hash, server_dict in self.grouped_by_txn.items():
|
||||
message_set = set()
|
||||
# message list is ordered by when it appears in the log
|
||||
message_list = []
|
||||
for server_id, messages in server_dict.items():
|
||||
for m in messages:
|
||||
try:
|
||||
d = m['data']
|
||||
if 'msg' in d and 'transaction' in d['msg']:
|
||||
t = d['msg']['transaction']
|
||||
elif 'tx_json' in d:
|
||||
t = d['tx_json']
|
||||
if t['hash'] == txn_hash:
|
||||
hash_to_txn[txn_hash] = t
|
||||
except:
|
||||
pass
|
||||
msg = m['msg']
|
||||
t = _to_timestamp(m['t'])
|
||||
if txn_hash not in hash_to_timestamp:
|
||||
hash_to_timestamp[txn_hash] = t
|
||||
elif hash_to_timestamp[txn_hash] > t:
|
||||
hash_to_timestamp[txn_hash] = t
|
||||
if msg not in message_set:
|
||||
message_set.add(msg)
|
||||
message_list.append(msg)
|
||||
df = pd.DataFrame(0,
|
||||
index=server_dict.keys(),
|
||||
columns=message_list)
|
||||
for server_id, messages in server_dict.items():
|
||||
for m in messages:
|
||||
df[m['msg']][server_id] += 1
|
||||
counts_by_txn_and_server[txn_hash] = df
|
||||
|
||||
# sort the transactions by timestamp, but the txns with unknown timestamp at the beginning
|
||||
self.grouped_by_txn = _rekey_dict_by_txn_date(hash_to_timestamp,
|
||||
self.grouped_by_txn)
|
||||
counts_by_txn_and_server = _rekey_dict_by_txn_date(
|
||||
hash_to_timestamp, counts_by_txn_and_server)
|
||||
|
||||
with open(self.grouped_by_txn_file_name, 'w') as out:
|
||||
print(json.dumps(self.grouped_by_txn, indent=1), file=out)
|
||||
|
||||
with open(self.counts_by_txn_and_server_file_name, 'w') as out:
|
||||
for txn_hash, df in counts_by_txn_and_server.items():
|
||||
print(f'\n\n* Txn: {txn_hash}', file=out)
|
||||
if txn_hash in hash_to_txn:
|
||||
print(json.dumps(hash_to_txn[txn_hash], indent=1),
|
||||
file=out)
|
||||
rename_dict = {}
|
||||
for column, renamed_column in zip(df.columns.array,
|
||||
string.ascii_uppercase):
|
||||
print(f'{renamed_column} = {column}', file=out)
|
||||
rename_dict[column] = renamed_column
|
||||
df.rename(columns=rename_dict, inplace=True)
|
||||
print(f'\n{df}', file=out)
|
||||
|
||||
def combine_logs(self):
|
||||
try:
|
||||
with open(self.combined_logs_file_name, "w") as out:
|
||||
log_analyzer.convert_all(args.input, out, pure_json=True)
|
||||
except Exception as e:
|
||||
eprint(f'Excption: {e}')
|
||||
raise e
|
||||
|
||||
|
||||
def main(input_dir_name: str, output_dir_name: str):
|
||||
r = Report(input_dir_name, output_dir_name)
|
||||
|
||||
# Values are a list of log lines formatted as json. There are five fields:
|
||||
# `t` is the timestamp.
|
||||
# `m` is the module.
|
||||
# `l` is the log level.
|
||||
# `msg` is the message.
|
||||
# `data` is the data.
|
||||
# For example:
|
||||
#
|
||||
# {
|
||||
# "t": "2021-Oct-08 21:33:41.731371562 UTC",
|
||||
# "m": "SidechainFederator",
|
||||
# "l": "TRC",
|
||||
# "msg": "no last xchain txn with result",
|
||||
# "data": {
|
||||
# "needsOtherChainLastXChainTxn": true,
|
||||
# "isMainchain": false,
|
||||
# "jlogId": 121
|
||||
# }
|
||||
# },
|
||||
|
||||
|
||||
# Lifecycle of a transaction
|
||||
# For each federator record:
|
||||
# Transaction detected: amount, seq, destination, chain, hash
|
||||
# Signature received: hash, seq
|
||||
# Signature sent: hash, seq, federator dst
|
||||
# Transaction submitted
|
||||
# Result received, and detect if error
|
||||
# Detect any field that doesn't match
|
||||
|
||||
# Lifecycle of initialization
|
||||
|
||||
# Chain listener messages
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description=(
|
||||
'python script to generate a log report from a sidechain config directory structure containing the logs'
|
||||
))
|
||||
|
||||
parser.add_argument(
|
||||
'--input',
|
||||
'-i',
|
||||
help=('directory with sidechain config directory structure'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--output',
|
||||
'-o',
|
||||
help=('output directory for report files'),
|
||||
)
|
||||
|
||||
return parser.parse_known_args()[0]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
args = parse_args()
|
||||
main(args.input, args.output)
|
||||
except Exception as e:
|
||||
eprint(f'Excption: {e}')
|
||||
raise e
|
||||
14
bin/sidechain/python/requirements.txt
Normal file
14
bin/sidechain/python/requirements.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
attrs==21.2.0
|
||||
iniconfig==1.1.1
|
||||
numpy==1.21.2
|
||||
packaging==21.0
|
||||
pandas==1.3.3
|
||||
pluggy==1.0.0
|
||||
py==1.10.0
|
||||
pyparsing==2.4.7
|
||||
pytest==6.2.5
|
||||
python-dateutil==2.8.2
|
||||
pytz==2021.1
|
||||
six==1.16.0
|
||||
toml==0.10.2
|
||||
websockets==8.1
|
||||
35
bin/sidechain/python/riplrepl.py
Executable file
35
bin/sidechain/python/riplrepl.py
Executable file
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
'''
|
||||
Script to run an interactive shell to test sidechains.
|
||||
'''
|
||||
|
||||
import sys
|
||||
|
||||
from common import disable_eprint, eprint
|
||||
import interactive
|
||||
import sidechain
|
||||
|
||||
|
||||
def main():
|
||||
params = sidechain.Params()
|
||||
params.interactive = True
|
||||
|
||||
interactive.set_hooks_dir(params.hooks_dir)
|
||||
|
||||
if err_str := params.check_error():
|
||||
eprint(err_str)
|
||||
sys.exit(1)
|
||||
|
||||
if params.verbose:
|
||||
print("eprint enabled")
|
||||
else:
|
||||
disable_eprint()
|
||||
|
||||
if params.standalone:
|
||||
sidechain.standalone_interactive_repl(params)
|
||||
else:
|
||||
sidechain.multinode_interactive_repl(params)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
193
bin/sidechain/python/ripple_client.py
Normal file
193
bin/sidechain/python/ripple_client.py
Normal file
@@ -0,0 +1,193 @@
|
||||
import asyncio
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from os.path import expanduser
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Callable, List, Optional, Union
|
||||
import time
|
||||
import websockets
|
||||
|
||||
from command import Command, ServerInfo, SubscriptionCommand
|
||||
from common import eprint
|
||||
from config_file import ConfigFile
|
||||
|
||||
|
||||
class RippleClient:
|
||||
'''Client to send commands to the rippled server'''
|
||||
def __init__(self,
|
||||
*,
|
||||
config: ConfigFile,
|
||||
exe: str,
|
||||
command_log: Optional[str] = None):
|
||||
self.config = config
|
||||
self.exe = exe
|
||||
self.command_log = command_log
|
||||
section = config.port_ws_admin_local
|
||||
self.websocket_uri = f'{section.protocol}://{section.ip}:{section.port}'
|
||||
self.subscription_websockets = []
|
||||
self.tasks = []
|
||||
self.pid = None
|
||||
if command_log:
|
||||
with open(self.command_log, 'w') as f:
|
||||
f.write(f'# Start \n')
|
||||
|
||||
@property
|
||||
def config_file_name(self):
|
||||
return self.config.get_file_name()
|
||||
|
||||
def shutdown(self):
|
||||
try:
|
||||
group = asyncio.gather(*self.tasks, return_exceptions=True)
|
||||
group.cancel()
|
||||
asyncio.get_event_loop().run_until_complete(group)
|
||||
for ws in self.subscription_websockets:
|
||||
asyncio.get_event_loop().run_until_complete(ws.close())
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
def set_pid(self, pid: int):
|
||||
self.pid = pid
|
||||
|
||||
def get_pid(self) -> Optional[int]:
|
||||
return self.pid
|
||||
|
||||
def get_config(self) -> ConfigFile:
|
||||
return self.config
|
||||
|
||||
# Get a dict of the server_state, validated_ledger_seq, and complete_ledgers
|
||||
def get_brief_server_info(self) -> dict:
|
||||
ret = {
|
||||
'server_state': 'NA',
|
||||
'ledger_seq': 'NA',
|
||||
'complete_ledgers': 'NA'
|
||||
}
|
||||
if not self.pid or self.pid == -1:
|
||||
return ret
|
||||
r = self.send_command(ServerInfo())
|
||||
if 'info' not in r:
|
||||
return ret
|
||||
r = r['info']
|
||||
for f in ['server_state', 'complete_ledgers']:
|
||||
if f in r:
|
||||
ret[f] = r[f]
|
||||
if 'validated_ledger' in r:
|
||||
ret['ledger_seq'] = r['validated_ledger']['seq']
|
||||
return ret
|
||||
|
||||
def _write_command_log_command(self, cmd: str, cmd_index: int) -> None:
|
||||
if not self.command_log:
|
||||
return
|
||||
with open(self.command_log, 'a') as f:
|
||||
f.write(f'\n\n# command {cmd_index}\n')
|
||||
f.write(f'{cmd}')
|
||||
|
||||
def _write_command_log_result(self, result: str, cmd_index: int) -> None:
|
||||
if not self.command_log:
|
||||
return
|
||||
with open(self.command_log, 'a') as f:
|
||||
f.write(f'\n\n# result {cmd_index}\n')
|
||||
f.write(f'{result}')
|
||||
|
||||
def _send_command_line_command(self, cmd_id: int, *args) -> dict:
|
||||
'''Send the command to the rippled server using the command line interface'''
|
||||
to_run = [self.exe, '-q', '--conf', self.config_file_name, '--']
|
||||
to_run.extend(args)
|
||||
self._write_command_log_command(to_run, cmd_id)
|
||||
max_retries = 4
|
||||
for retry_count in range(0, max_retries + 1):
|
||||
try:
|
||||
r = subprocess.check_output(to_run)
|
||||
self._write_command_log_result(r, cmd_id)
|
||||
return json.loads(r.decode('utf-8'))['result']
|
||||
except Exception as e:
|
||||
if retry_count == max_retries:
|
||||
raise
|
||||
eprint(
|
||||
f'Got exception: {str(e)}\nretrying..{retry_count+1} of {max_retries}'
|
||||
)
|
||||
time.sleep(1) # give process time to startup
|
||||
|
||||
async def _send_websock_command(
|
||||
self,
|
||||
cmd: Command,
|
||||
conn: Optional[websockets.client.Connect] = None) -> dict:
|
||||
assert self.websocket_uri
|
||||
if conn is None:
|
||||
async with websockets.connect(self.websocket_uri) as ws:
|
||||
return await self._send_websock_command(cmd, ws)
|
||||
|
||||
to_send = json.dumps(cmd.get_websocket_dict())
|
||||
self._write_command_log_command(to_send, cmd.cmd_id)
|
||||
await conn.send(to_send)
|
||||
r = await conn.recv()
|
||||
self._write_command_log_result(r, cmd.cmd_id)
|
||||
j = json.loads(r)
|
||||
if not 'result' in j:
|
||||
eprint(
|
||||
f'Error sending websocket command: {json.dumps(cmd.get_websocket_dict(), indent=1)}'
|
||||
)
|
||||
eprint(f'Result: {json.dumps(j, indent=1)}')
|
||||
raise ValueError('Error sending websocket command')
|
||||
return j['result']
|
||||
|
||||
def send_command(self, cmd: Command) -> dict:
|
||||
'''Send the command to the rippled server'''
|
||||
if self.websocket_uri:
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
self._send_websock_command(cmd))
|
||||
return self._send_command_line_command(cmd.cmd_id,
|
||||
*cmd.get_command_line_list())
|
||||
|
||||
# Need async version to close ledgers from async functions
|
||||
async def async_send_command(self, cmd: Command) -> dict:
|
||||
'''Send the command to the rippled server'''
|
||||
if self.websocket_uri:
|
||||
return await self._send_websock_command(cmd)
|
||||
return self._send_command_line_command(cmd.cmd_id,
|
||||
*cmd.get_command_line_list())
|
||||
|
||||
def send_subscribe_command(
|
||||
self,
|
||||
cmd: SubscriptionCommand,
|
||||
callback: Optional[Callable[[dict], None]] = None) -> dict:
|
||||
'''Send the command to the rippled server'''
|
||||
assert self.websocket_uri
|
||||
ws = cmd.websocket
|
||||
if ws is None:
|
||||
# subscribe
|
||||
assert callback
|
||||
ws = asyncio.get_event_loop().run_until_complete(
|
||||
websockets.connect(self.websocket_uri))
|
||||
self.subscription_websockets.append(ws)
|
||||
result = asyncio.get_event_loop().run_until_complete(
|
||||
self._send_websock_command(cmd, ws))
|
||||
if cmd.websocket is not None:
|
||||
# unsubscribed. close the websocket
|
||||
self.subscription_websockets.remove(cmd.websocket)
|
||||
cmd.websocket.close()
|
||||
cmd.websocket = None
|
||||
else:
|
||||
# setup a task to read the websocket
|
||||
cmd.websocket = ws # must be set after the _send_websock_command or will unsubscribe
|
||||
|
||||
async def subscribe_callback(ws: websockets.client.Connect,
|
||||
cb: Callable[[dict], None]):
|
||||
while True:
|
||||
r = await ws.recv()
|
||||
d = json.loads(r)
|
||||
cb(d)
|
||||
|
||||
task = asyncio.get_event_loop().create_task(
|
||||
subscribe_callback(cmd.websocket, callback))
|
||||
self.tasks.append(task)
|
||||
return result
|
||||
|
||||
def stop(self):
|
||||
'''Stop the server'''
|
||||
return self.send_command(Stop())
|
||||
|
||||
def set_log_level(self, severity: str, *, partition: Optional[str] = None):
|
||||
'''Set the server log level'''
|
||||
return self.send_command(LogLevel(severity, parition=parition))
|
||||
583
bin/sidechain/python/sidechain.py
Executable file
583
bin/sidechain/python/sidechain.py
Executable file
@@ -0,0 +1,583 @@
|
||||
#!/usr/bin/env python3
|
||||
'''
|
||||
Script to test and debug sidechains.
|
||||
|
||||
The mainchain exe location can be set through the command line or
|
||||
the environment variable RIPPLED_MAINCHAIN_EXE
|
||||
|
||||
The sidechain exe location can be set through the command line or
|
||||
the environment variable RIPPLED_SIDECHAIN_EXE
|
||||
|
||||
The configs_dir (generated with create_config_files.py) can be set through the command line
|
||||
or the environment variable RIPPLED_SIDECHAIN_CFG_DIR
|
||||
'''
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from multiprocessing import Process, Value
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import Callable, Dict, List, Optional
|
||||
|
||||
from app import App, single_client_app, testnet_app, configs_for_testnet
|
||||
from command import AccountInfo, AccountTx, LedgerAccept, LogLevel, Subscribe
|
||||
from common import Account, Asset, eprint, disable_eprint, XRP
|
||||
from config_file import ConfigFile
|
||||
import interactive
|
||||
from log_analyzer import convert_log
|
||||
from test_utils import mc_wait_for_payment_detect, sc_wait_for_payment_detect, mc_connect_subscription, sc_connect_subscription
|
||||
from transaction import AccountSet, Payment, SignerListSet, SetRegularKey, Ticket, Trust
|
||||
|
||||
|
||||
def parse_args_helper(parser: argparse.ArgumentParser):
|
||||
|
||||
parser.add_argument(
|
||||
'--debug_sidechain',
|
||||
'-ds',
|
||||
action='store_true',
|
||||
help=('Mode to debug sidechain (prompt to run sidechain in gdb)'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--debug_mainchain',
|
||||
'-dm',
|
||||
action='store_true',
|
||||
help=('Mode to debug mainchain (prompt to run sidechain in gdb)'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--exe_mainchain',
|
||||
'-em',
|
||||
help=('path to mainchain rippled executable'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--exe_sidechain',
|
||||
'-es',
|
||||
help=('path to mainchain rippled executable'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--cfgs_dir',
|
||||
'-c',
|
||||
help=
|
||||
('path to configuration file dir (generated with create_config_files.py)'
|
||||
),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--standalone',
|
||||
'-a',
|
||||
action='store_true',
|
||||
help=('run standalone tests'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--interactive',
|
||||
'-i',
|
||||
action='store_true',
|
||||
help=('run interactive repl'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--quiet',
|
||||
'-q',
|
||||
action='store_true',
|
||||
help=('Disable printing errors (eprint disabled)'),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--verbose',
|
||||
'-v',
|
||||
action='store_true',
|
||||
help=('Enable printing errors (eprint enabled)'),
|
||||
)
|
||||
|
||||
# Pauses are use for attaching debuggers and looking at logs are know checkpoints
|
||||
parser.add_argument(
|
||||
'--with_pauses',
|
||||
'-p',
|
||||
action='store_true',
|
||||
help=
|
||||
('Add pauses at certain checkpoints in tests until "enter" key is hit'
|
||||
),
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'--hooks_dir',
|
||||
help=('path to hooks dir'),
|
||||
)
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description=('Test and debug sidechains'))
|
||||
parse_args_helper(parser)
|
||||
return parser.parse_known_args()[0]
|
||||
|
||||
|
||||
class Params:
|
||||
def __init__(self, *, configs_dir: Optional[str] = None):
|
||||
args = parse_args()
|
||||
|
||||
self.debug_sidechain = False
|
||||
if args.debug_sidechain:
|
||||
self.debug_sidechain = args.debug_sidechain
|
||||
self.debug_mainchain = False
|
||||
if args.debug_mainchain:
|
||||
self.debug_mainchain = arts.debug_mainchain
|
||||
|
||||
# Undocumented feature: if the environment variable RIPPLED_SIDECHAIN_RR is set, it is
|
||||
# assumed to point to the rr executable. Sidechain server 0 will then be run under rr.
|
||||
self.sidechain_rr = None
|
||||
if 'RIPPLED_SIDECHAIN_RR' in os.environ:
|
||||
self.sidechain_rr = os.environ['RIPPLED_SIDECHAIN_RR']
|
||||
|
||||
self.standalone = args.standalone
|
||||
self.with_pauses = args.with_pauses
|
||||
self.interactive = args.interactive
|
||||
self.quiet = args.quiet
|
||||
self.verbose = args.verbose
|
||||
|
||||
self.mainchain_exe = None
|
||||
if 'RIPPLED_MAINCHAIN_EXE' in os.environ:
|
||||
self.mainchain_exe = os.environ['RIPPLED_MAINCHAIN_EXE']
|
||||
if args.exe_mainchain:
|
||||
self.mainchain_exe = args.exe_mainchain
|
||||
|
||||
self.sidechain_exe = None
|
||||
if 'RIPPLED_SIDECHAIN_EXE' in os.environ:
|
||||
self.sidechain_exe = os.environ['RIPPLED_SIDECHAIN_EXE']
|
||||
if args.exe_sidechain:
|
||||
self.sidechain_exe = args.exe_sidechain
|
||||
|
||||
self.configs_dir = None
|
||||
if 'RIPPLED_SIDECHAIN_CFG_DIR' in os.environ:
|
||||
self.configs_dir = os.environ['RIPPLED_SIDECHAIN_CFG_DIR']
|
||||
if args.cfgs_dir:
|
||||
self.configs_dir = args.cfgs_dir
|
||||
if configs_dir is not None:
|
||||
self.configs_dir = configs_dir
|
||||
|
||||
self.hooks_dir = None
|
||||
if 'RIPPLED_SIDECHAIN_HOOKS_DIR' in os.environ:
|
||||
self.hooks_dir = os.environ['RIPPLED_SIDECHAIN_HOOKS_DIR']
|
||||
if args.hooks_dir:
|
||||
self.hooks_dir = args.hooks_dir
|
||||
|
||||
if not self.configs_dir:
|
||||
self.mainchain_config = None
|
||||
self.sidechain_config = None
|
||||
self.sidechain_bootstrap_config = None
|
||||
self.genesis_account = None
|
||||
self.mc_door_account = None
|
||||
self.user_account = None
|
||||
self.sc_door_account = None
|
||||
self.federators = None
|
||||
return
|
||||
|
||||
if self.standalone:
|
||||
self.mainchain_config = ConfigFile(
|
||||
file_name=f'{self.configs_dir}/main.no_shards.dog/rippled.cfg')
|
||||
self.sidechain_config = ConfigFile(
|
||||
file_name=
|
||||
f'{self.configs_dir}/main.no_shards.dog.sidechain/rippled.cfg')
|
||||
self.sidechain_bootstrap_config = ConfigFile(
|
||||
file_name=
|
||||
f'{self.configs_dir}/main.no_shards.dog.sidechain/sidechain_bootstrap.cfg'
|
||||
)
|
||||
else:
|
||||
self.mainchain_config = ConfigFile(
|
||||
file_name=
|
||||
f'{self.configs_dir}/sidechain_testnet/main.no_shards.mainchain_0/rippled.cfg'
|
||||
)
|
||||
self.sidechain_config = ConfigFile(
|
||||
file_name=
|
||||
f'{self.configs_dir}/sidechain_testnet/sidechain_0/rippled.cfg'
|
||||
)
|
||||
self.sidechain_bootstrap_config = ConfigFile(
|
||||
file_name=
|
||||
f'{self.configs_dir}/sidechain_testnet/sidechain_0/sidechain_bootstrap.cfg'
|
||||
)
|
||||
|
||||
self.genesis_account = Account(
|
||||
account_id='rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
|
||||
secret_key='masterpassphrase',
|
||||
nickname='genesis')
|
||||
self.mc_door_account = Account(
|
||||
account_id=self.sidechain_config.sidechain.mainchain_account,
|
||||
secret_key=self.sidechain_bootstrap_config.sidechain.
|
||||
mainchain_secret,
|
||||
nickname='door')
|
||||
self.user_account = Account(
|
||||
account_id='rJynXY96Vuq6B58pST9K5Ak5KgJ2JcRsQy',
|
||||
secret_key='snVsJfrr2MbVpniNiUU6EDMGBbtzN',
|
||||
nickname='alice')
|
||||
|
||||
self.sc_door_account = Account(
|
||||
account_id='rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
|
||||
secret_key='masterpassphrase',
|
||||
nickname='door')
|
||||
self.federators = [
|
||||
l.split()[1].strip() for l in
|
||||
self.sidechain_bootstrap_config.sidechain_federators.get_lines()
|
||||
]
|
||||
|
||||
def check_error(self) -> str:
|
||||
'''
|
||||
Check for errors. Return `None` if no errors,
|
||||
otherwise return a string describing the error
|
||||
'''
|
||||
if not self.mainchain_exe:
|
||||
return 'Missing mainchain_exe location. Either set the env variable RIPPLED_MAINCHAIN_EXE or use the --exe_mainchain command line switch'
|
||||
if not self.sidechain_exe:
|
||||
return 'Missing sidechain_exe location. Either set the env variable RIPPLED_SIDECHAIN_EXE or use the --exe_sidechain command line switch'
|
||||
if not self.configs_dir:
|
||||
return 'Missing configs directory location. Either set the env variable RIPPLED_SIDECHAIN_CFG_DIR or use the --cfgs_dir command line switch'
|
||||
if self.verbose and self.quiet:
|
||||
return 'Cannot specify both verbose and quiet options at the same time'
|
||||
|
||||
|
||||
mainDoorKeeper = 0
|
||||
sideDoorKeeper = 1
|
||||
updateSignerList = 2
|
||||
|
||||
|
||||
def setup_mainchain(mc_app: App,
|
||||
params: Params,
|
||||
setup_user_accounts: bool = True):
|
||||
mc_app.add_to_keymanager(params.mc_door_account)
|
||||
if setup_user_accounts:
|
||||
mc_app.add_to_keymanager(params.user_account)
|
||||
|
||||
mc_app(LogLevel('fatal'))
|
||||
|
||||
# Allow rippling through the genesis account
|
||||
mc_app(AccountSet(account=params.genesis_account).set_default_ripple(True))
|
||||
mc_app.maybe_ledger_accept()
|
||||
|
||||
# Create and fund the mc door account
|
||||
mc_app(
|
||||
Payment(account=params.genesis_account,
|
||||
dst=params.mc_door_account,
|
||||
amt=XRP(10_000)))
|
||||
mc_app.maybe_ledger_accept()
|
||||
|
||||
# Create a trust line so USD/root account ious can be sent cross chain
|
||||
mc_app(
|
||||
Trust(account=params.mc_door_account,
|
||||
limit_amt=Asset(value=1_000_000,
|
||||
currency='USD',
|
||||
issuer=params.genesis_account)))
|
||||
|
||||
# set the chain's signer list and disable the master key
|
||||
divide = 4 * len(params.federators)
|
||||
by = 5
|
||||
quorum = (divide + by - 1) // by
|
||||
mc_app(
|
||||
SignerListSet(account=params.mc_door_account,
|
||||
quorum=quorum,
|
||||
keys=params.federators))
|
||||
mc_app.maybe_ledger_accept()
|
||||
r = mc_app(Ticket(account=params.mc_door_account, src_tag=mainDoorKeeper))
|
||||
mc_app.maybe_ledger_accept()
|
||||
mc_app(Ticket(account=params.mc_door_account, src_tag=sideDoorKeeper))
|
||||
mc_app.maybe_ledger_accept()
|
||||
mc_app(Ticket(account=params.mc_door_account, src_tag=updateSignerList))
|
||||
mc_app.maybe_ledger_accept()
|
||||
mc_app(AccountSet(account=params.mc_door_account).set_disable_master())
|
||||
mc_app.maybe_ledger_accept()
|
||||
|
||||
if setup_user_accounts:
|
||||
# Create and fund a regular user account
|
||||
mc_app(
|
||||
Payment(account=params.genesis_account,
|
||||
dst=params.user_account,
|
||||
amt=XRP(2_000)))
|
||||
mc_app.maybe_ledger_accept()
|
||||
|
||||
|
||||
def setup_sidechain(sc_app: App,
|
||||
params: Params,
|
||||
setup_user_accounts: bool = True):
|
||||
sc_app.add_to_keymanager(params.sc_door_account)
|
||||
if setup_user_accounts:
|
||||
sc_app.add_to_keymanager(params.user_account)
|
||||
|
||||
sc_app(LogLevel('fatal'))
|
||||
sc_app(LogLevel('trace', partition='SidechainFederator'))
|
||||
|
||||
# set the chain's signer list and disable the master key
|
||||
divide = 4 * len(params.federators)
|
||||
by = 5
|
||||
quorum = (divide + by - 1) // by
|
||||
sc_app(
|
||||
SignerListSet(account=params.genesis_account,
|
||||
quorum=quorum,
|
||||
keys=params.federators))
|
||||
sc_app.maybe_ledger_accept()
|
||||
sc_app(Ticket(account=params.genesis_account, src_tag=mainDoorKeeper))
|
||||
sc_app.maybe_ledger_accept()
|
||||
sc_app(Ticket(account=params.genesis_account, src_tag=sideDoorKeeper))
|
||||
sc_app.maybe_ledger_accept()
|
||||
sc_app(Ticket(account=params.genesis_account, src_tag=updateSignerList))
|
||||
sc_app.maybe_ledger_accept()
|
||||
sc_app(AccountSet(account=params.genesis_account).set_disable_master())
|
||||
sc_app.maybe_ledger_accept()
|
||||
|
||||
|
||||
def _xchain_transfer(from_chain: App, to_chain: App, src: Account,
|
||||
dst: Account, amt: Asset, from_chain_door: Account,
|
||||
to_chain_door: Account):
|
||||
memos = [{'Memo': {'MemoData': dst.account_id_str_as_hex()}}]
|
||||
from_chain(Payment(account=src, dst=from_chain_door, amt=amt, memos=memos))
|
||||
from_chain.maybe_ledger_accept()
|
||||
if to_chain.standalone:
|
||||
# from_chain (side chain) sends a txn, but won't close the to_chain (main chain) ledger
|
||||
time.sleep(1)
|
||||
to_chain.maybe_ledger_accept()
|
||||
|
||||
|
||||
def main_to_side_transfer(mc_app: App, sc_app: App, src: Account, dst: Account,
|
||||
amt: Asset, params: Params):
|
||||
_xchain_transfer(mc_app, sc_app, src, dst, amt, params.mc_door_account,
|
||||
params.sc_door_account)
|
||||
|
||||
|
||||
def side_to_main_transfer(mc_app: App, sc_app: App, src: Account, dst: Account,
|
||||
amt: Asset, params: Params):
|
||||
_xchain_transfer(sc_app, mc_app, src, dst, amt, params.sc_door_account,
|
||||
params.mc_door_account)
|
||||
|
||||
|
||||
def simple_test(mc_app: App, sc_app: App, params: Params):
|
||||
try:
|
||||
bob = sc_app.create_account('bob')
|
||||
main_to_side_transfer(mc_app, sc_app, params.user_account, bob,
|
||||
XRP(200), params)
|
||||
main_to_side_transfer(mc_app, sc_app, params.user_account, bob,
|
||||
XRP(60), params)
|
||||
|
||||
if params.with_pauses:
|
||||
_convert_log_files_to_json(
|
||||
mc_app.get_configs() + sc_app.get_configs(),
|
||||
'checkpoint1.json')
|
||||
input(
|
||||
"Pausing to check for main -> side txns (press enter to continue)"
|
||||
)
|
||||
|
||||
side_to_main_transfer(mc_app, sc_app, bob, params.user_account, XRP(9),
|
||||
params)
|
||||
side_to_main_transfer(mc_app, sc_app, bob, params.user_account,
|
||||
XRP(11), params)
|
||||
|
||||
if params.with_pauses:
|
||||
input(
|
||||
"Pausing to check for side -> main txns (press enter to continue)"
|
||||
)
|
||||
finally:
|
||||
_convert_log_files_to_json(mc_app.get_configs() + sc_app.get_configs(),
|
||||
'final.json')
|
||||
|
||||
|
||||
def _rm_debug_log(config: ConfigFile):
|
||||
try:
|
||||
debug_log = config.debug_logfile.get_line()
|
||||
if debug_log:
|
||||
print(f'removing debug file: {debug_log}', flush=True)
|
||||
os.remove(debug_log)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
def _standalone_with_callback(params: Params,
|
||||
callback: Callable[[App, App], None],
|
||||
setup_user_accounts: bool = True):
|
||||
|
||||
if (params.debug_mainchain):
|
||||
input("Start mainchain server and press enter to continue: ")
|
||||
else:
|
||||
_rm_debug_log(params.mainchain_config)
|
||||
with single_client_app(config=params.mainchain_config,
|
||||
exe=params.mainchain_exe,
|
||||
standalone=True,
|
||||
run_server=not params.debug_mainchain) as mc_app:
|
||||
|
||||
mc_connect_subscription(mc_app, params.mc_door_account)
|
||||
setup_mainchain(mc_app, params, setup_user_accounts)
|
||||
|
||||
if (params.debug_sidechain):
|
||||
input("Start sidechain server and press enter to continue: ")
|
||||
else:
|
||||
_rm_debug_log(params.sidechain_config)
|
||||
with single_client_app(
|
||||
config=params.sidechain_config,
|
||||
exe=params.sidechain_exe,
|
||||
standalone=True,
|
||||
run_server=not params.debug_sidechain) as sc_app:
|
||||
|
||||
sc_connect_subscription(sc_app, params.sc_door_account)
|
||||
setup_sidechain(sc_app, params, setup_user_accounts)
|
||||
callback(mc_app, sc_app)
|
||||
|
||||
|
||||
def _convert_log_files_to_json(to_convert: List[ConfigFile], suffix: str):
|
||||
'''
|
||||
Convert the log file to json
|
||||
'''
|
||||
for c in to_convert:
|
||||
try:
|
||||
debug_log = c.debug_logfile.get_line()
|
||||
if not os.path.exists(debug_log):
|
||||
continue
|
||||
converted_log = f'{debug_log}.{suffix}'
|
||||
if os.path.exists(converted_log):
|
||||
os.remove(converted_log)
|
||||
print(f'Converting log {debug_log} to {converted_log}', flush=True)
|
||||
convert_log(debug_log, converted_log, pure_json=True)
|
||||
except:
|
||||
eprint(f'Exception converting log')
|
||||
|
||||
|
||||
def _multinode_with_callback(params: Params,
|
||||
callback: Callable[[App, App], None],
|
||||
setup_user_accounts: bool = True):
|
||||
|
||||
mainchain_cfg = ConfigFile(
|
||||
file_name=
|
||||
f'{params.configs_dir}/sidechain_testnet/main.no_shards.mainchain_0/rippled.cfg'
|
||||
)
|
||||
_rm_debug_log(mainchain_cfg)
|
||||
if params.debug_mainchain:
|
||||
input("Start mainchain server and press enter to continue: ")
|
||||
with single_client_app(config=mainchain_cfg,
|
||||
exe=params.mainchain_exe,
|
||||
standalone=True,
|
||||
run_server=not params.debug_mainchain) as mc_app:
|
||||
|
||||
if params.with_pauses:
|
||||
input("Pausing after mainchain start (press enter to continue)")
|
||||
|
||||
mc_connect_subscription(mc_app, params.mc_door_account)
|
||||
setup_mainchain(mc_app, params, setup_user_accounts)
|
||||
if params.with_pauses:
|
||||
input("Pausing after mainchain setup (press enter to continue)")
|
||||
|
||||
testnet_configs = configs_for_testnet(
|
||||
f'{params.configs_dir}/sidechain_testnet/sidechain_')
|
||||
for c in testnet_configs:
|
||||
_rm_debug_log(c)
|
||||
|
||||
run_server_list = [True] * len(testnet_configs)
|
||||
if params.debug_sidechain:
|
||||
run_server_list[0] = False
|
||||
input(
|
||||
f'Start testnet server {testnet_configs[0].get_file_name()} and press enter to continue: '
|
||||
)
|
||||
|
||||
with testnet_app(exe=params.sidechain_exe,
|
||||
configs=testnet_configs,
|
||||
run_server=run_server_list,
|
||||
sidechain_rr=params.sidechain_rr) as n_app:
|
||||
|
||||
if params.with_pauses:
|
||||
input("Pausing after testnet start (press enter to continue)")
|
||||
|
||||
sc_connect_subscription(n_app, params.sc_door_account)
|
||||
setup_sidechain(n_app, params, setup_user_accounts)
|
||||
if params.with_pauses:
|
||||
input(
|
||||
"Pausing after sidechain setup (press enter to continue)")
|
||||
callback(mc_app, n_app)
|
||||
|
||||
|
||||
def standalone_test(params: Params):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
simple_test(mc_app, sc_app, params)
|
||||
|
||||
_standalone_with_callback(params, callback)
|
||||
|
||||
|
||||
def multinode_test(params: Params):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
simple_test(mc_app, sc_app, params)
|
||||
|
||||
_multinode_with_callback(params, callback)
|
||||
|
||||
|
||||
# The mainchain runs in standalone mode. Most operations - like cross chain
|
||||
# paymens - will automatically close ledgers. However, some operations, like
|
||||
# refunds need an extra close. This loop automatically closes ledgers.
|
||||
def close_mainchain_ledgers(stop_token: Value, params: Params, sleep_time=4):
|
||||
with single_client_app(config=params.mainchain_config,
|
||||
exe=params.mainchain_exe,
|
||||
standalone=True,
|
||||
run_server=False) as mc_app:
|
||||
while stop_token.value != 0:
|
||||
mc_app.maybe_ledger_accept()
|
||||
time.sleep(sleep_time)
|
||||
|
||||
|
||||
def standalone_interactive_repl(params: Params):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
# process will run while stop token is non-zero
|
||||
stop_token = Value('i', 1)
|
||||
p = None
|
||||
if mc_app.standalone:
|
||||
p = Process(target=close_mainchain_ledgers,
|
||||
args=(stop_token, params))
|
||||
p.start()
|
||||
try:
|
||||
interactive.repl(mc_app, sc_app)
|
||||
finally:
|
||||
if p:
|
||||
stop_token.value = 0
|
||||
p.join()
|
||||
|
||||
_standalone_with_callback(params, callback, setup_user_accounts=False)
|
||||
|
||||
|
||||
def multinode_interactive_repl(params: Params):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
# process will run while stop token is non-zero
|
||||
stop_token = Value('i', 1)
|
||||
p = None
|
||||
if mc_app.standalone:
|
||||
p = Process(target=close_mainchain_ledgers,
|
||||
args=(stop_token, params))
|
||||
p.start()
|
||||
try:
|
||||
interactive.repl(mc_app, sc_app)
|
||||
finally:
|
||||
if p:
|
||||
stop_token.value = 0
|
||||
p.join()
|
||||
|
||||
_multinode_with_callback(params, callback, setup_user_accounts=False)
|
||||
|
||||
|
||||
def main():
|
||||
params = Params()
|
||||
interactive.set_hooks_dir(params.hooks_dir)
|
||||
|
||||
if err_str := params.check_error():
|
||||
eprint(err_str)
|
||||
sys.exit(1)
|
||||
|
||||
if params.quiet:
|
||||
print("Disabling eprint")
|
||||
disable_eprint()
|
||||
|
||||
if params.interactive:
|
||||
if params.standalone:
|
||||
standalone_interactive_repl(params)
|
||||
else:
|
||||
multinode_interactive_repl(params)
|
||||
elif params.standalone:
|
||||
standalone_test(params)
|
||||
else:
|
||||
multinode_test(params)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
176
bin/sidechain/python/test_utils.py
Normal file
176
bin/sidechain/python/test_utils.py
Normal file
@@ -0,0 +1,176 @@
|
||||
import asyncio
|
||||
import collections
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import logging
|
||||
import pprint
|
||||
import time
|
||||
from typing import Callable, Dict, List, Optional
|
||||
|
||||
from app import App, balances_dataframe
|
||||
from common import Account, Asset, XRP, eprint
|
||||
from command import Subscribe
|
||||
|
||||
MC_SUBSCRIBE_QUEUE = []
|
||||
SC_SUBSCRIBE_QUEUE = []
|
||||
|
||||
|
||||
def _mc_subscribe_callback(v: dict):
|
||||
MC_SUBSCRIBE_QUEUE.append(v)
|
||||
logging.info(f'mc subscribe_callback:\n{json.dumps(v, indent=1)}')
|
||||
|
||||
|
||||
def _sc_subscribe_callback(v: dict):
|
||||
SC_SUBSCRIBE_QUEUE.append(v)
|
||||
logging.info(f'sc subscribe_callback:\n{json.dumps(v, indent=1)}')
|
||||
|
||||
|
||||
def mc_connect_subscription(app: App, door_account: Account):
|
||||
app(Subscribe(account_history_account=door_account),
|
||||
_mc_subscribe_callback)
|
||||
|
||||
|
||||
def sc_connect_subscription(app: App, door_account: Account):
|
||||
app(Subscribe(account_history_account=door_account),
|
||||
_sc_subscribe_callback)
|
||||
|
||||
|
||||
# This pops elements off the subscribe_queue until the transaction is found
|
||||
# It mofifies the queue in place.
|
||||
async def async_wait_for_payment_detect(app: App, subscribe_queue: List[dict],
|
||||
src: Account, dst: Account,
|
||||
amt_asset: Asset):
|
||||
logging.info(
|
||||
f'Wait for payment {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
n_txns = 10 # keep this many txn in a circular buffer.
|
||||
# If the payment is not detected, write them to the log.
|
||||
last_n_paytxns = collections.deque(maxlen=n_txns)
|
||||
for i in range(30):
|
||||
while subscribe_queue:
|
||||
d = subscribe_queue.pop(0)
|
||||
if 'transaction' not in d:
|
||||
continue
|
||||
txn = d['transaction']
|
||||
if txn['TransactionType'] != 'Payment':
|
||||
continue
|
||||
|
||||
txn_asset = Asset(from_rpc_result=txn['Amount'])
|
||||
if txn['Account'] == src.account_id and txn[
|
||||
'Destination'] == dst.account_id and txn_asset == amt_asset:
|
||||
if d['engine_result_code'] == 0:
|
||||
logging.info(
|
||||
f'Found payment {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
return
|
||||
else:
|
||||
logging.error(
|
||||
f'Expected payment failed {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
raise ValueError(
|
||||
f'Expected payment failed {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
else:
|
||||
last_n_paytxns.append(txn)
|
||||
if i > 0 and not (i % 5):
|
||||
logging.warning(
|
||||
f'Waiting for txn detect {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
# side chain can send transactions to the main chain, but won't close the ledger
|
||||
# We don't know when the transaction will be sent, so may need to close the ledger here
|
||||
await app.async_maybe_ledger_accept()
|
||||
await asyncio.sleep(2)
|
||||
logging.warning(
|
||||
f'Last {len(last_n_paytxns)} pay txns while waiting for payment detect'
|
||||
)
|
||||
for t in last_n_paytxns:
|
||||
logging.warning(
|
||||
f'Detected pay transaction while waiting for payment: {t}')
|
||||
logging.error(
|
||||
f'Expected txn detect {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
raise ValueError(
|
||||
f'Expected txn detect {src.account_id = } {dst.account_id = } {amt_asset = }'
|
||||
)
|
||||
|
||||
|
||||
def mc_wait_for_payment_detect(app: App, src: Account, dst: Account,
|
||||
amt_asset: Asset):
|
||||
logging.info(f'mainchain waiting for payment detect')
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
async_wait_for_payment_detect(app, MC_SUBSCRIBE_QUEUE, src, dst,
|
||||
amt_asset))
|
||||
|
||||
|
||||
def sc_wait_for_payment_detect(app: App, src: Account, dst: Account,
|
||||
amt_asset: Asset):
|
||||
logging.info(f'sidechain waiting for payment detect')
|
||||
return asyncio.get_event_loop().run_until_complete(
|
||||
async_wait_for_payment_detect(app, SC_SUBSCRIBE_QUEUE, src, dst,
|
||||
amt_asset))
|
||||
|
||||
|
||||
def wait_for_balance_change(app: App,
|
||||
acc: Account,
|
||||
pre_balance: Asset,
|
||||
expected_diff: Optional[Asset] = None):
|
||||
logging.info(
|
||||
f'waiting for balance change {acc.account_id = } {pre_balance = } {expected_diff = }'
|
||||
)
|
||||
for i in range(30):
|
||||
new_bal = app.get_balance(acc, pre_balance(0))
|
||||
diff = new_bal - pre_balance
|
||||
if new_bal != pre_balance:
|
||||
logging.info(
|
||||
f'Balance changed {acc.account_id = } {pre_balance = } {new_bal = } {diff = } {expected_diff = }'
|
||||
)
|
||||
if expected_diff is None or diff == expected_diff:
|
||||
return
|
||||
app.maybe_ledger_accept()
|
||||
time.sleep(2)
|
||||
if i > 0 and not (i % 5):
|
||||
logging.warning(
|
||||
f'Waiting for balance to change {acc.account_id = } {pre_balance = }'
|
||||
)
|
||||
logging.error(
|
||||
f'Expected balance to change {acc.account_id = } {pre_balance = } {new_bal = } {diff = } {expected_diff = }'
|
||||
)
|
||||
raise ValueError(
|
||||
f'Expected balance to change {acc.account_id = } {pre_balance = } {new_bal = } {diff = } {expected_diff = }'
|
||||
)
|
||||
|
||||
|
||||
def log_chain_state(mc_app, sc_app, log, msg='Chain State'):
|
||||
chains = [mc_app, sc_app]
|
||||
chain_names = ['mainchain', 'sidechain']
|
||||
balances = balances_dataframe(chains, chain_names)
|
||||
df_as_str = balances.to_string(float_format=lambda x: f'{x:,.6f}')
|
||||
log(f'{msg} Balances: \n{df_as_str}')
|
||||
federator_info = sc_app.federator_info()
|
||||
log(f'{msg} Federator Info: \n{pprint.pformat(federator_info)}')
|
||||
|
||||
|
||||
# Tests can set this to True to help debug test failures by showing account
|
||||
# balances in the log before the test runs
|
||||
test_context_verbose_logging = False
|
||||
|
||||
|
||||
@contextmanager
|
||||
def test_context(mc_app, sc_app, verbose_logging: Optional[bool] = None):
|
||||
'''Write extra context info to the log on test failure'''
|
||||
global test_context_verbose_logging
|
||||
if verbose_logging is None:
|
||||
verbose_logging = test_context_verbose_logging
|
||||
try:
|
||||
if verbose_logging:
|
||||
log_chain_state(mc_app, sc_app, logging.info)
|
||||
start_time = time.monotonic()
|
||||
yield
|
||||
except:
|
||||
log_chain_state(mc_app, sc_app, logging.error)
|
||||
raise
|
||||
finally:
|
||||
elapased_time = time.monotonic() - start_time
|
||||
logging.info(f'Test elapsed time: {elapased_time}')
|
||||
if verbose_logging:
|
||||
log_chain_state(mc_app, sc_app, logging.info)
|
||||
216
bin/sidechain/python/testnet.py
Normal file
216
bin/sidechain/python/testnet.py
Normal file
@@ -0,0 +1,216 @@
|
||||
'''
|
||||
Bring up a rippled testnetwork from a set of config files with fixed ips.
|
||||
'''
|
||||
|
||||
from contextlib import contextmanager
|
||||
import glob
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Callable, List, Optional, Set, Union
|
||||
|
||||
from command import ServerInfo
|
||||
from config_file import ConfigFile
|
||||
from ripple_client import RippleClient
|
||||
|
||||
|
||||
class Network:
|
||||
# If run_server is None, run all the servers.
|
||||
# This is useful to help debugging
|
||||
def __init__(
|
||||
self,
|
||||
exe: str,
|
||||
configs: List[ConfigFile],
|
||||
*,
|
||||
command_logs: Optional[List[str]] = None,
|
||||
run_server: Optional[List[bool]] = None,
|
||||
# undocumented feature. If with_rr is not None, assume it points to the rr debugger executable
|
||||
# and run server 0 under rr
|
||||
with_rr: Optional[str] = None,
|
||||
extra_args: Optional[List[List[str]]] = None):
|
||||
|
||||
self.with_rr = with_rr
|
||||
if not configs:
|
||||
raise ValueError(f'Must specify at least one config')
|
||||
|
||||
if run_server and len(run_server) != len(configs):
|
||||
raise ValueError(
|
||||
f'run_server length must match number of configs (or be None): {len(configs) = } {len(run_server) = }'
|
||||
)
|
||||
|
||||
self.configs = configs
|
||||
self.clients = []
|
||||
self.running_server_indexes = set()
|
||||
self.processes = {}
|
||||
|
||||
if not run_server:
|
||||
run_server = []
|
||||
run_server += [True] * (len(configs) - len(run_server))
|
||||
|
||||
self.run_server = run_server
|
||||
|
||||
if not command_logs:
|
||||
command_logs = []
|
||||
command_logs += [None] * (len(configs) - len(command_logs))
|
||||
|
||||
self.command_logs = command_logs
|
||||
|
||||
# remove the old database directories.
|
||||
# we want tests to start from the same empty state every time
|
||||
for config in self.configs:
|
||||
db_path = config.database_path.get_line()
|
||||
if db_path and os.path.isdir(db_path):
|
||||
files = glob.glob(f'{db_path}/**', recursive=True)
|
||||
for f in files:
|
||||
if os.path.isdir(f):
|
||||
continue
|
||||
os.unlink(f)
|
||||
|
||||
for config, log in zip(self.configs, self.command_logs):
|
||||
client = RippleClient(config=config, command_log=log, exe=exe)
|
||||
self.clients.append(client)
|
||||
|
||||
self.servers_start(extra_args=extra_args)
|
||||
|
||||
def shutdown(self):
|
||||
for a in self.clients:
|
||||
a.shutdown()
|
||||
|
||||
self.servers_stop()
|
||||
|
||||
def num_clients(self) -> int:
|
||||
return len(self.clients)
|
||||
|
||||
def get_client(self, i: int) -> RippleClient:
|
||||
return self.clients[i]
|
||||
|
||||
def get_configs(self) -> List[ConfigFile]:
|
||||
return [c.config for c in self.clients]
|
||||
|
||||
def get_pids(self) -> List[int]:
|
||||
return [c.get_pid() for c in self.clients if c.get_pid() is not None]
|
||||
|
||||
# Get a dict of the server_state, validated_ledger_seq, and complete_ledgers
|
||||
def get_brief_server_info(self) -> dict:
|
||||
ret = {'server_state': [], 'ledger_seq': [], 'complete_ledgers': []}
|
||||
for c in self.clients:
|
||||
r = c.get_brief_server_info()
|
||||
for (k, v) in r.items():
|
||||
ret[k].append(v)
|
||||
return ret
|
||||
|
||||
# returns true if the server is running, false if not. Note, this relies on
|
||||
# servers being shut down through the `servers_stop` interface. If a server
|
||||
# crashes, or is started or stopped through other means, an incorrect status
|
||||
# may be reported.
|
||||
def get_running_status(self) -> List[bool]:
|
||||
return [
|
||||
i in self.running_server_indexes for i in range(len(self.clients))
|
||||
]
|
||||
|
||||
def is_running(self, index: int) -> bool:
|
||||
return index in self.running_server_indexes
|
||||
|
||||
def wait_for_validated_ledger(self, server_index: Optional[int] = None):
|
||||
'''
|
||||
Don't return until the network has at least one validated ledger
|
||||
'''
|
||||
|
||||
if server_index is None:
|
||||
for i in range(len(self.configs)):
|
||||
self.wait_for_validated_ledger(i)
|
||||
return
|
||||
|
||||
client = self.clients[server_index]
|
||||
for i in range(600):
|
||||
r = client.send_command(ServerInfo())
|
||||
state = None
|
||||
if 'info' in r:
|
||||
state = r['info']['server_state']
|
||||
if state == 'proposing':
|
||||
print(f'Synced: {server_index} : {state}', flush=True)
|
||||
break
|
||||
if not i % 10:
|
||||
print(f'Waiting for sync: {server_index} : {state}',
|
||||
flush=True)
|
||||
time.sleep(1)
|
||||
|
||||
for i in range(600):
|
||||
r = client.send_command(ServerInfo())
|
||||
state = None
|
||||
if 'info' in r:
|
||||
complete_ledgers = r['info']['complete_ledgers']
|
||||
if complete_ledgers and complete_ledgers != 'empty':
|
||||
print(f'Have complete ledgers: {server_index} : {state}',
|
||||
flush=True)
|
||||
return
|
||||
if not i % 10:
|
||||
print(
|
||||
f'Waiting for complete_ledgers: {server_index} : {complete_ledgers}',
|
||||
flush=True)
|
||||
time.sleep(1)
|
||||
|
||||
raise ValueError('Could not sync server {client.config_file_name}')
|
||||
|
||||
def servers_start(self,
|
||||
server_indexes: Optional[Union[Set[int],
|
||||
List[int]]] = None,
|
||||
*,
|
||||
extra_args: Optional[List[List[str]]] = None):
|
||||
if server_indexes is None:
|
||||
server_indexes = [i for i in range(len(self.clients))]
|
||||
|
||||
if extra_args is None:
|
||||
extra_args = []
|
||||
extra_args += [list()] * (len(self.configs) - len(extra_args))
|
||||
|
||||
for i in server_indexes:
|
||||
if i in self.running_server_indexes or not self.run_server[i]:
|
||||
continue
|
||||
|
||||
client = self.clients[i]
|
||||
to_run = [client.exe, '--conf', client.config_file_name]
|
||||
if self.with_rr and i == 0:
|
||||
to_run = [self.with_rr, 'record'] + to_run
|
||||
print(f'Starting server with rr {client.config_file_name}')
|
||||
else:
|
||||
print(f'Starting server {client.config_file_name}')
|
||||
fout = open(os.devnull, 'w')
|
||||
p = subprocess.Popen(to_run + extra_args[i],
|
||||
stdout=fout,
|
||||
stderr=subprocess.STDOUT)
|
||||
client.set_pid(p.pid)
|
||||
print(
|
||||
f'started rippled: config: {client.config_file_name} PID: {p.pid}',
|
||||
flush=True)
|
||||
self.running_server_indexes.add(i)
|
||||
self.processes[i] = p
|
||||
|
||||
time.sleep(2) # give servers time to start
|
||||
|
||||
def servers_stop(self,
|
||||
server_indexes: Optional[Union[Set[int],
|
||||
List[int]]] = None):
|
||||
if server_indexes is None:
|
||||
server_indexes = self.running_server_indexes.copy()
|
||||
|
||||
if 0 in server_indexes:
|
||||
print(
|
||||
f'WARNING: Server 0 is being stopped. RPC commands cannot be sent until this is restarted.'
|
||||
)
|
||||
|
||||
for i in server_indexes:
|
||||
if i not in self.running_server_indexes:
|
||||
continue
|
||||
client = self.clients[i]
|
||||
to_run = [client.exe, '--conf', client.config_file_name]
|
||||
fout = open(os.devnull, 'w')
|
||||
subprocess.Popen(to_run + ['stop'],
|
||||
stdout=fout,
|
||||
stderr=subprocess.STDOUT)
|
||||
self.running_server_indexes.discard(i)
|
||||
|
||||
for i in server_indexes:
|
||||
self.processes[i].wait()
|
||||
del self.processes[i]
|
||||
self.get_client(i).set_pid(-1)
|
||||
64
bin/sidechain/python/tests/conftest.py
Normal file
64
bin/sidechain/python/tests/conftest.py
Normal file
@@ -0,0 +1,64 @@
|
||||
# Add parent directory to module path
|
||||
import os, sys
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from common import Account, Asset, XRP
|
||||
import create_config_files
|
||||
import sidechain
|
||||
|
||||
import pytest
|
||||
'''
|
||||
Sidechains uses argparse.ArgumentParser to add command line options.
|
||||
The function call to add an argument is `add_argument`. pytest uses `addoption`.
|
||||
This wrapper class changes calls from `add_argument` to calls to `addoption`.
|
||||
To avoid conflicts between pytest and sidechains, all sidechain arguments have
|
||||
the suffix `_sc` appended to them. I.e. `--verbose` is for pytest, `--verbose_sc`
|
||||
is for sidechains.
|
||||
'''
|
||||
|
||||
|
||||
class ArgumentParserWrapper:
|
||||
def __init__(self, wrapped):
|
||||
self.wrapped = wrapped
|
||||
|
||||
def add_argument(self, *args, **kwargs):
|
||||
for a in args:
|
||||
if not a.startswith('--'):
|
||||
continue
|
||||
a = a + '_sc'
|
||||
self.wrapped.addoption(a, **kwargs)
|
||||
|
||||
|
||||
def pytest_addoption(parser):
|
||||
wrapped = ArgumentParserWrapper(parser)
|
||||
sidechain.parse_args_helper(wrapped)
|
||||
|
||||
|
||||
def _xchain_assets(ratio: int = 1):
|
||||
assets = {}
|
||||
assets['xrp_xrp_sidechain_asset'] = create_config_files.XChainAsset(
|
||||
XRP(0), XRP(0), 1, 1 * ratio, 200, 200 * ratio)
|
||||
root_account = Account(account_id="rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")
|
||||
main_iou_asset = Asset(value=0, currency='USD', issuer=root_account)
|
||||
side_iou_asset = Asset(value=0, currency='USD', issuer=root_account)
|
||||
assets['iou_iou_sidechain_asset'] = create_config_files.XChainAsset(
|
||||
main_iou_asset, side_iou_asset, 1, 1 * ratio, 0.02, 0.02 * ratio)
|
||||
return assets
|
||||
|
||||
|
||||
# Diction of config dirs. Key is ratio
|
||||
_config_dirs = None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def configs_dirs_dict(tmp_path):
|
||||
global _config_dirs
|
||||
if not _config_dirs:
|
||||
params = create_config_files.Params()
|
||||
_config_dirs = {}
|
||||
for ratio in (1, 2):
|
||||
params.configs_dir = str(tmp_path / f'test_config_files_{ratio}')
|
||||
create_config_files.main(params, _xchain_assets(ratio))
|
||||
_config_dirs[ratio] = params.configs_dir
|
||||
|
||||
return _config_dirs
|
||||
117
bin/sidechain/python/tests/door_test.py
Normal file
117
bin/sidechain/python/tests/door_test.py
Normal file
@@ -0,0 +1,117 @@
|
||||
from typing import Dict
|
||||
from app import App
|
||||
from common import XRP
|
||||
from sidechain import Params
|
||||
import sidechain
|
||||
import test_utils
|
||||
import time
|
||||
from transaction import Payment
|
||||
import tst_common
|
||||
|
||||
batch_test_num_accounts = 200
|
||||
|
||||
|
||||
def door_test(mc_app: App, sc_app: App, params: Params):
|
||||
# setup, create accounts on both chains
|
||||
for i in range(batch_test_num_accounts):
|
||||
name = "m_" + str(i)
|
||||
account_main = mc_app.create_account(name)
|
||||
name = "s_" + str(i)
|
||||
account_side = sc_app.create_account(name)
|
||||
mc_app(
|
||||
Payment(account=params.genesis_account,
|
||||
dst=account_main,
|
||||
amt=XRP(20_000)))
|
||||
mc_app.maybe_ledger_accept()
|
||||
account_main_last = mc_app.account_from_alias("m_" +
|
||||
str(batch_test_num_accounts -
|
||||
1))
|
||||
test_utils.wait_for_balance_change(mc_app, account_main_last, XRP(0),
|
||||
XRP(20_000))
|
||||
|
||||
# test
|
||||
to_side_xrp = XRP(1000)
|
||||
to_main_xrp = XRP(100)
|
||||
last_tx_xrp = XRP(343)
|
||||
with test_utils.test_context(mc_app, sc_app, True):
|
||||
# send xchain payment to open accounts on sidechain
|
||||
for i in range(batch_test_num_accounts):
|
||||
name_main = "m_" + str(i)
|
||||
account_main = mc_app.account_from_alias(name_main)
|
||||
name_side = "s_" + str(i)
|
||||
account_side = sc_app.account_from_alias(name_side)
|
||||
memos = [{
|
||||
'Memo': {
|
||||
'MemoData': account_side.account_id_str_as_hex()
|
||||
}
|
||||
}]
|
||||
mc_app(
|
||||
Payment(account=account_main,
|
||||
dst=params.mc_door_account,
|
||||
amt=to_side_xrp,
|
||||
memos=memos))
|
||||
|
||||
while 1:
|
||||
federator_info = sc_app.federator_info()
|
||||
should_loop = False
|
||||
for v in federator_info.values():
|
||||
for c in ['mainchain', 'sidechain']:
|
||||
state = v['info'][c]['listener_info']['state']
|
||||
if state != 'normal':
|
||||
should_loop = True
|
||||
if not should_loop:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
# wait some time for the door to change
|
||||
door_closing = False
|
||||
door_reopened = False
|
||||
for i in range(batch_test_num_accounts * 2 + 40):
|
||||
server_index = [0]
|
||||
federator_info = sc_app.federator_info(server_index)
|
||||
for v in federator_info.values():
|
||||
door_status = v['info']['mainchain']['door_status']['status']
|
||||
if not door_closing:
|
||||
if door_status != 'open':
|
||||
door_closing = True
|
||||
else:
|
||||
if door_status == 'open':
|
||||
door_reopened = True
|
||||
|
||||
if not door_reopened:
|
||||
time.sleep(1)
|
||||
mc_app.maybe_ledger_accept()
|
||||
else:
|
||||
break
|
||||
|
||||
if not door_reopened:
|
||||
raise ValueError('Expected door status changes did not happen')
|
||||
|
||||
# wait for accounts created on sidechain
|
||||
for i in range(batch_test_num_accounts):
|
||||
name_side = "s_" + str(i)
|
||||
account_side = sc_app.account_from_alias(name_side)
|
||||
test_utils.wait_for_balance_change(sc_app, account_side, XRP(0),
|
||||
to_side_xrp)
|
||||
|
||||
# # try one xchain payment, each direction
|
||||
name_main = "m_" + str(0)
|
||||
account_main = mc_app.account_from_alias(name_main)
|
||||
name_side = "s_" + str(0)
|
||||
account_side = sc_app.account_from_alias(name_side)
|
||||
|
||||
pre_bal = mc_app.get_balance(account_main, XRP(0))
|
||||
sidechain.side_to_main_transfer(mc_app, sc_app, account_side,
|
||||
account_main, to_main_xrp, params)
|
||||
test_utils.wait_for_balance_change(mc_app, account_main, pre_bal,
|
||||
to_main_xrp)
|
||||
|
||||
pre_bal = sc_app.get_balance(account_side, XRP(0))
|
||||
sidechain.main_to_side_transfer(mc_app, sc_app, account_main,
|
||||
account_side, last_tx_xrp, params)
|
||||
test_utils.wait_for_balance_change(sc_app, account_side, pre_bal,
|
||||
last_tx_xrp)
|
||||
|
||||
|
||||
def test_door_operations(configs_dirs_dict: Dict[int, str]):
|
||||
tst_common.test_start(configs_dirs_dict, door_test)
|
||||
151
bin/sidechain/python/tests/simple_xchain_transfer_test.py
Normal file
151
bin/sidechain/python/tests/simple_xchain_transfer_test.py
Normal file
@@ -0,0 +1,151 @@
|
||||
import logging
|
||||
import pprint
|
||||
import pytest
|
||||
from multiprocessing import Process, Value
|
||||
from typing import Dict
|
||||
import sys
|
||||
|
||||
from app import App
|
||||
from common import Asset, eprint, disable_eprint, drops, XRP
|
||||
import interactive
|
||||
from sidechain import Params
|
||||
import sidechain
|
||||
import test_utils
|
||||
import time
|
||||
from transaction import Payment, Trust
|
||||
import tst_common
|
||||
|
||||
|
||||
def simple_xrp_test(mc_app: App, sc_app: App, params: Params):
|
||||
alice = mc_app.account_from_alias('alice')
|
||||
adam = sc_app.account_from_alias('adam')
|
||||
mc_door = mc_app.account_from_alias('door')
|
||||
sc_door = sc_app.account_from_alias('door')
|
||||
|
||||
# main to side
|
||||
# First txn funds the side chain account
|
||||
with test_utils.test_context(mc_app, sc_app):
|
||||
to_send_asset = XRP(9999)
|
||||
mc_pre_bal = mc_app.get_balance(mc_door, to_send_asset)
|
||||
sc_pre_bal = sc_app.get_balance(adam, to_send_asset)
|
||||
sidechain.main_to_side_transfer(mc_app, sc_app, alice, adam,
|
||||
to_send_asset, params)
|
||||
test_utils.wait_for_balance_change(mc_app, mc_door, mc_pre_bal,
|
||||
to_send_asset)
|
||||
test_utils.wait_for_balance_change(sc_app, adam, sc_pre_bal,
|
||||
to_send_asset)
|
||||
|
||||
for i in range(2):
|
||||
# even amounts for main to side
|
||||
for value in range(20, 30, 2):
|
||||
with test_utils.test_context(mc_app, sc_app):
|
||||
to_send_asset = drops(value)
|
||||
mc_pre_bal = mc_app.get_balance(mc_door, to_send_asset)
|
||||
sc_pre_bal = sc_app.get_balance(adam, to_send_asset)
|
||||
sidechain.main_to_side_transfer(mc_app, sc_app, alice, adam,
|
||||
to_send_asset, params)
|
||||
test_utils.wait_for_balance_change(mc_app, mc_door, mc_pre_bal,
|
||||
to_send_asset)
|
||||
test_utils.wait_for_balance_change(sc_app, adam, sc_pre_bal,
|
||||
to_send_asset)
|
||||
|
||||
# side to main
|
||||
# odd amounts for side to main
|
||||
for value in range(19, 29, 2):
|
||||
with test_utils.test_context(mc_app, sc_app):
|
||||
to_send_asset = drops(value)
|
||||
pre_bal = mc_app.get_balance(alice, to_send_asset)
|
||||
sidechain.side_to_main_transfer(mc_app, sc_app, adam, alice,
|
||||
to_send_asset, params)
|
||||
test_utils.wait_for_balance_change(mc_app, alice, pre_bal,
|
||||
to_send_asset)
|
||||
|
||||
|
||||
def simple_iou_test(mc_app: App, sc_app: App, params: Params):
|
||||
alice = mc_app.account_from_alias('alice')
|
||||
adam = sc_app.account_from_alias('adam')
|
||||
|
||||
mc_asset = Asset(value=0,
|
||||
currency='USD',
|
||||
issuer=mc_app.account_from_alias('root'))
|
||||
sc_asset = Asset(value=0,
|
||||
currency='USD',
|
||||
issuer=sc_app.account_from_alias('door'))
|
||||
mc_app.add_asset_alias(mc_asset, 'mcd') # main chain dollar
|
||||
sc_app.add_asset_alias(sc_asset, 'scd') # side chain dollar
|
||||
mc_app(Trust(account=alice, limit_amt=mc_asset(1_000_000)))
|
||||
|
||||
## make sure adam account on the side chain exists and set the trust line
|
||||
with test_utils.test_context(mc_app, sc_app):
|
||||
sidechain.main_to_side_transfer(mc_app, sc_app, alice, adam, XRP(300),
|
||||
params)
|
||||
|
||||
# create a trust line to alice and pay her USD/root
|
||||
mc_app(Trust(account=alice, limit_amt=mc_asset(1_000_000)))
|
||||
mc_app.maybe_ledger_accept()
|
||||
mc_app(
|
||||
Payment(account=mc_app.account_from_alias('root'),
|
||||
dst=alice,
|
||||
amt=mc_asset(10_000)))
|
||||
mc_app.maybe_ledger_accept()
|
||||
|
||||
# create a trust line for adam
|
||||
sc_app(Trust(account=adam, limit_amt=sc_asset(1_000_000)))
|
||||
|
||||
for i in range(2):
|
||||
# even amounts for main to side
|
||||
for value in range(10, 20, 2):
|
||||
with test_utils.test_context(mc_app, sc_app):
|
||||
to_send_asset = mc_asset(value)
|
||||
rcv_asset = sc_asset(value)
|
||||
pre_bal = sc_app.get_balance(adam, rcv_asset)
|
||||
sidechain.main_to_side_transfer(mc_app, sc_app, alice, adam,
|
||||
to_send_asset, params)
|
||||
test_utils.wait_for_balance_change(sc_app, adam, pre_bal,
|
||||
rcv_asset)
|
||||
|
||||
# side to main
|
||||
# odd amounts for side to main
|
||||
for value in range(9, 19, 2):
|
||||
with test_utils.test_context(mc_app, sc_app):
|
||||
to_send_asset = sc_asset(value)
|
||||
rcv_asset = mc_asset(value)
|
||||
pre_bal = mc_app.get_balance(alice, to_send_asset)
|
||||
sidechain.side_to_main_transfer(mc_app, sc_app, adam, alice,
|
||||
to_send_asset, params)
|
||||
test_utils.wait_for_balance_change(mc_app, alice, pre_bal,
|
||||
rcv_asset)
|
||||
|
||||
|
||||
def setup_accounts(mc_app: App, sc_app: App, params: Params):
|
||||
# Setup a funded user account on the main chain, and add an unfunded account.
|
||||
# Setup address book and add a funded account on the mainchain.
|
||||
# Typical female names are addresses on the mainchain.
|
||||
# The first account is funded.
|
||||
alice = mc_app.create_account('alice')
|
||||
beth = mc_app.create_account('beth')
|
||||
carol = mc_app.create_account('carol')
|
||||
deb = mc_app.create_account('deb')
|
||||
ella = mc_app.create_account('ella')
|
||||
mc_app(Payment(account=params.genesis_account, dst=alice, amt=XRP(20_000)))
|
||||
mc_app.maybe_ledger_accept()
|
||||
|
||||
# Typical male names are addresses on the sidechain.
|
||||
# All accounts are initially unfunded
|
||||
adam = sc_app.create_account('adam')
|
||||
bob = sc_app.create_account('bob')
|
||||
charlie = sc_app.create_account('charlie')
|
||||
dan = sc_app.create_account('dan')
|
||||
ed = sc_app.create_account('ed')
|
||||
|
||||
|
||||
def run_all(mc_app: App, sc_app: App, params: Params):
|
||||
setup_accounts(mc_app, sc_app, params)
|
||||
logging.info(f'mainchain:\n{mc_app.key_manager.to_string()}')
|
||||
logging.info(f'sidechain:\n{sc_app.key_manager.to_string()}')
|
||||
simple_xrp_test(mc_app, sc_app, params)
|
||||
simple_iou_test(mc_app, sc_app, params)
|
||||
|
||||
|
||||
def test_simple_xchain(configs_dirs_dict: Dict[int, str]):
|
||||
tst_common.test_start(configs_dirs_dict, run_all)
|
||||
74
bin/sidechain/python/tests/tst_common.py
Normal file
74
bin/sidechain/python/tests/tst_common.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import logging
|
||||
import pprint
|
||||
import pytest
|
||||
from multiprocessing import Process, Value
|
||||
from typing import Callable, Dict
|
||||
import sys
|
||||
|
||||
from app import App
|
||||
from common import eprint, disable_eprint, XRP
|
||||
from sidechain import Params
|
||||
import sidechain
|
||||
import test_utils
|
||||
import time
|
||||
|
||||
|
||||
def run(mc_app: App, sc_app: App, params: Params,
|
||||
test_case: Callable[[App, App, Params], None]):
|
||||
# process will run while stop token is non-zero
|
||||
stop_token = Value('i', 1)
|
||||
p = None
|
||||
if mc_app.standalone:
|
||||
p = Process(target=sidechain.close_mainchain_ledgers,
|
||||
args=(stop_token, params))
|
||||
p.start()
|
||||
try:
|
||||
test_case(mc_app, sc_app, params)
|
||||
finally:
|
||||
if p:
|
||||
stop_token.value = 0
|
||||
p.join()
|
||||
sidechain._convert_log_files_to_json(
|
||||
mc_app.get_configs() + sc_app.get_configs(), 'final.json')
|
||||
|
||||
|
||||
def standalone_test(params: Params, test_case: Callable[[App, App, Params],
|
||||
None]):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
run(mc_app, sc_app, params, test_case)
|
||||
|
||||
sidechain._standalone_with_callback(params,
|
||||
callback,
|
||||
setup_user_accounts=False)
|
||||
|
||||
|
||||
def multinode_test(params: Params, test_case: Callable[[App, App, Params],
|
||||
None]):
|
||||
def callback(mc_app: App, sc_app: App):
|
||||
run(mc_app, sc_app, params, test_case)
|
||||
|
||||
sidechain._multinode_with_callback(params,
|
||||
callback,
|
||||
setup_user_accounts=False)
|
||||
|
||||
|
||||
def test_start(configs_dirs_dict: Dict[int, str],
|
||||
test_case: Callable[[App, App, Params], None]):
|
||||
params = sidechain.Params(configs_dir=configs_dirs_dict[1])
|
||||
|
||||
if err_str := params.check_error():
|
||||
eprint(err_str)
|
||||
sys.exit(1)
|
||||
|
||||
if params.verbose:
|
||||
print("eprint enabled")
|
||||
else:
|
||||
disable_eprint()
|
||||
|
||||
# Set to true to help debug tests
|
||||
test_utils.test_context_verbose_logging = True
|
||||
|
||||
if params.standalone:
|
||||
standalone_test(params, test_case)
|
||||
else:
|
||||
multinode_test(params, test_case)
|
||||
366
bin/sidechain/python/transaction.py
Normal file
366
bin/sidechain/python/transaction.py
Normal file
@@ -0,0 +1,366 @@
|
||||
import datetime
|
||||
import json
|
||||
from typing import Dict, List, Optional, Union
|
||||
|
||||
from command import Command
|
||||
from common import Account, Asset, Path, PathList, to_rippled_epoch
|
||||
|
||||
|
||||
class Transaction(Command):
|
||||
'''Interface for all transactions'''
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
account: Account,
|
||||
flags: Optional[int] = None,
|
||||
fee: Optional[Union[Asset, int]] = None,
|
||||
sequence: Optional[int] = None,
|
||||
account_txn_id: Optional[str] = None,
|
||||
last_ledger_sequence: Optional[int] = None,
|
||||
src_tag: Optional[int] = None,
|
||||
memos: Optional[List[Dict[str, dict]]] = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.account = account
|
||||
# set even if None
|
||||
self.flags = flags
|
||||
self.fee = fee
|
||||
self.sequence = sequence
|
||||
self.account_txn_id = account_txn_id
|
||||
self.last_ledger_sequence = last_ledger_sequence
|
||||
self.src_tag = src_tag
|
||||
self.memos = memos
|
||||
|
||||
def cmd_name(self) -> str:
|
||||
return 'submit'
|
||||
|
||||
def set_seq_and_fee(self, seq: int, fee: Union[Asset, int]):
|
||||
self.sequence = seq
|
||||
self.fee = fee
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
txn = {
|
||||
'Account': self.account.account_id,
|
||||
}
|
||||
if self.flags is not None:
|
||||
txn['Flags'] = flags
|
||||
if self.fee is not None:
|
||||
if isinstance(self.fee, int):
|
||||
txn['Fee'] = f'{self.fee}' # must be a string
|
||||
else:
|
||||
txn['Fee'] = self.fee.to_cmd_obj()
|
||||
if self.sequence is not None:
|
||||
txn['Sequence'] = self.sequence
|
||||
if self.account_txn_id is not None:
|
||||
txn['AccountTxnID'] = self.account_txn_id
|
||||
if self.last_ledger_sequence is not None:
|
||||
txn['LastLedgerSequence'] = self.last_ledger_sequence
|
||||
if self.src_tag is not None:
|
||||
txn['SourceTag'] = self.src_tag
|
||||
if self.memos is not None:
|
||||
txn['Memos'] = self.memos
|
||||
return txn
|
||||
|
||||
|
||||
class Payment(Transaction):
|
||||
'''A payment transaction'''
|
||||
def __init__(self,
|
||||
*,
|
||||
dst: Account,
|
||||
amt: Asset,
|
||||
send_max: Optional[Asset] = None,
|
||||
paths: Optional[PathList] = None,
|
||||
dst_tag: Optional[int] = None,
|
||||
deliver_min: Optional[Asset] = None,
|
||||
**rest):
|
||||
super().__init__(**rest)
|
||||
self.dst = dst
|
||||
self.amt = amt
|
||||
self.send_max = send_max
|
||||
if paths is not None and isinstance(paths, Path):
|
||||
# allow paths = Path([...]) special case
|
||||
self.paths = PathList([paths])
|
||||
else:
|
||||
self.paths = paths
|
||||
self.dst_tag = dst_tag
|
||||
self.deliver_min = deliver_min
|
||||
|
||||
def set_partial_payment(self, value: bool = True):
|
||||
'''Set or clear the partial payment flag'''
|
||||
self._set_flag(0x0002_0000, value)
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''convert to transaction form (suitable for using json.dumps or similar)'''
|
||||
txn = super().to_cmd_obj()
|
||||
txn = {
|
||||
**txn,
|
||||
'TransactionType': 'Payment',
|
||||
'Destination': self.dst.account_id,
|
||||
'Amount': self.amt.to_cmd_obj(),
|
||||
}
|
||||
if self.paths is not None:
|
||||
txn['Paths'] = self.paths.to_cmd_obj()
|
||||
if self.send_max is not None:
|
||||
txn['SendMax'] = self.send_max.to_cmd_obj()
|
||||
if self.dst_tag is not None:
|
||||
txn['DestinationTag'] = self.dst_tag
|
||||
if self.deliver_min is not None:
|
||||
txn['DeliverMin'] = self.deliver_min
|
||||
return txn
|
||||
|
||||
|
||||
class Trust(Transaction):
|
||||
'''A trust set transaction'''
|
||||
def __init__(self,
|
||||
*,
|
||||
limit_amt: Optional[Asset] = None,
|
||||
qin: Optional[int] = None,
|
||||
qout: Optional[int] = None,
|
||||
**rest):
|
||||
super().__init__(**rest)
|
||||
self.limit_amt = limit_amt
|
||||
self.qin = qin
|
||||
self.qout = qout
|
||||
|
||||
def set_auth(self):
|
||||
'''Set the auth flag (cannot be cleared)'''
|
||||
self._set_flag(0x00010000)
|
||||
return self
|
||||
|
||||
def set_no_ripple(self, value: bool = True):
|
||||
'''Set or clear the noRipple flag'''
|
||||
self._set_flag(0x0002_0000, value)
|
||||
self._set_flag(0x0004_0000, not value)
|
||||
return self
|
||||
|
||||
def set_freeze(self, value: bool = True):
|
||||
'''Set or clear the freeze flag'''
|
||||
self._set_flag(0x0020_0000, value)
|
||||
self._set_flag(0x0040_0000, not value)
|
||||
return self
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''convert to transaction form (suitable for using json.dumps or similar)'''
|
||||
result = super().to_cmd_obj()
|
||||
result = {
|
||||
**result,
|
||||
'TransactionType': 'TrustSet',
|
||||
'LimitAmount': self.limit_amt.to_cmd_obj(),
|
||||
}
|
||||
if self.qin is not None:
|
||||
result['QualityIn'] = self.qin
|
||||
if self.qout is not None:
|
||||
result['QualityOut'] = self.qout
|
||||
return result
|
||||
|
||||
|
||||
class SetRegularKey(Transaction):
|
||||
'''A SetRegularKey transaction'''
|
||||
def __init__(self, *, key: str, **rest):
|
||||
super().__init__(**rest)
|
||||
self.key = key
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''convert to transaction form (suitable for using json.dumps or similar)'''
|
||||
result = super().to_cmd_obj()
|
||||
result = {
|
||||
**result,
|
||||
'TransactionType': 'SetRegularKey',
|
||||
'RegularKey': self.key,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
class SignerListSet(Transaction):
|
||||
'''A SignerListSet transaction'''
|
||||
def __init__(self,
|
||||
*,
|
||||
keys: List[str],
|
||||
weights: Optional[List[int]] = None,
|
||||
quorum: int,
|
||||
**rest):
|
||||
super().__init__(**rest)
|
||||
self.keys = keys
|
||||
self.quorum = quorum
|
||||
if weights:
|
||||
if len(weights) != len(keys):
|
||||
raise ValueError(
|
||||
f'SignerSetList number of weights must equal number of keys (or be empty). Weights: {weights} Keys: {keys}'
|
||||
)
|
||||
self.weights = weights
|
||||
else:
|
||||
self.weights = [1] * len(keys)
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''convert to transaction form (suitable for using json.dumps or similar)'''
|
||||
result = super().to_cmd_obj()
|
||||
result = {
|
||||
**result,
|
||||
'TransactionType': 'SignerListSet',
|
||||
'SignerQuorum': self.quorum,
|
||||
}
|
||||
entries = []
|
||||
for k, w in zip(self.keys, self.weights):
|
||||
entries.append({'SignerEntry': {'Account': k, 'SignerWeight': w}})
|
||||
result['SignerEntries'] = entries
|
||||
return result
|
||||
|
||||
|
||||
class AccountSet(Transaction):
|
||||
'''An account set transaction'''
|
||||
def __init__(self, account: Account, **rest):
|
||||
super().__init__(account=account, **rest)
|
||||
self.clear_flag = None
|
||||
self.set_flag = None
|
||||
self.transfer_rate = None
|
||||
self.tick_size = None
|
||||
|
||||
def _set_account_flag(self, flag_id: int, value):
|
||||
if value:
|
||||
self.set_flag = flag_id
|
||||
else:
|
||||
self.clear_flag = flag_id
|
||||
return self
|
||||
|
||||
def set_account_txn_id(self, value: bool = True):
|
||||
'''Set or clear the asfAccountTxnID flag'''
|
||||
return self._set_account_flag(5, value)
|
||||
|
||||
def set_default_ripple(self, value: bool = True):
|
||||
'''Set or clear the asfDefaultRipple flag'''
|
||||
return self._set_account_flag(8, value)
|
||||
|
||||
def set_deposit_auth(self, value: bool = True):
|
||||
'''Set or clear the asfDepositAuth flag'''
|
||||
return self._set_account_flag(9, value)
|
||||
|
||||
def set_disable_master(self, value: bool = True):
|
||||
'''Set or clear the asfDisableMaster flag'''
|
||||
return self._set_account_flag(4, value)
|
||||
|
||||
def set_disallow_xrp(self, value: bool = True):
|
||||
'''Set or clear the asfDisallowXRP flag'''
|
||||
return self._set_account_flag(3, value)
|
||||
|
||||
def set_global_freeze(self, value: bool = True):
|
||||
'''Set or clear the asfGlobalFreeze flag'''
|
||||
return self._set_account_flag(7, value)
|
||||
|
||||
def set_no_freeze(self, value: bool = True):
|
||||
'''Set or clear the asfNoFreeze flag'''
|
||||
return self._set_account_flag(6, value)
|
||||
|
||||
def set_require_auth(self, value: bool = True):
|
||||
'''Set or clear the asfRequireAuth flag'''
|
||||
return self._set_account_flag(2, value)
|
||||
|
||||
def set_require_dest(self, value: bool = True):
|
||||
'''Set or clear the asfRequireDest flag'''
|
||||
return self._set_account_flag(1, value)
|
||||
|
||||
def set_transfer_rate(self, value: int):
|
||||
'''Set the fee to change when users transfer this account's issued currencies'''
|
||||
self.transfer_rate = value
|
||||
return self
|
||||
|
||||
def set_tick_size(self, value: int):
|
||||
'''Tick size to use for offers involving a currency issued by this address'''
|
||||
self.tick_size = value
|
||||
return self
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
'''convert to transaction form (suitable for using json.dumps or similar)'''
|
||||
result = super().to_cmd_obj()
|
||||
result = {
|
||||
**result,
|
||||
'TransactionType': 'AccountSet',
|
||||
}
|
||||
if self.clear_flag is not None:
|
||||
result['ClearFlag'] = self.clear_flag
|
||||
if self.set_flag is not None:
|
||||
result['SetFlag'] = self.set_flag
|
||||
if self.transfer_rate is not None:
|
||||
result['TransferRate'] = self.transfer_rate
|
||||
if self.tick_size is not None:
|
||||
result['TickSize'] = self.tick_size
|
||||
return result
|
||||
|
||||
|
||||
class Offer(Transaction):
|
||||
'''An offer transaction'''
|
||||
def __init__(self,
|
||||
*,
|
||||
taker_pays: Asset,
|
||||
taker_gets: Asset,
|
||||
expiration: Optional[int] = None,
|
||||
offer_sequence: Optional[int] = None,
|
||||
**rest):
|
||||
super().__init__(**rest)
|
||||
self.taker_pays = taker_pays
|
||||
self.taker_gets = taker_gets
|
||||
self.expiration = expiration
|
||||
self.offer_sequence = offer_sequence
|
||||
|
||||
def set_passive(self, value: bool = True):
|
||||
return self._set_flag(0x0001_0000, value)
|
||||
|
||||
def set_immediate_or_cancel(self, value: bool = True):
|
||||
return self._set_flag(0x0002_0000, value)
|
||||
|
||||
def set_fill_or_kill(self, value: bool = True):
|
||||
return self._set_flag(0x0004_0000, value)
|
||||
|
||||
def set_sell(self, value: bool = True):
|
||||
return self._set_flag(0x0008_0000, value)
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
txn = super().to_cmd_obj()
|
||||
txn = {
|
||||
**txn,
|
||||
'TransactionType': 'OfferCreate',
|
||||
'TakerPays': self.taker_pays.to_cmd_obj(),
|
||||
'TakerGets': self.taker_gets.to_cmd_obj(),
|
||||
}
|
||||
if self.expiration is not None:
|
||||
txn['Expiration'] = self.expiration
|
||||
if self.offer_sequence is not None:
|
||||
txn['OfferSequence'] = self.offer_sequence
|
||||
return txn
|
||||
|
||||
|
||||
class Ticket(Transaction):
|
||||
'''A ticket create transaction'''
|
||||
def __init__(self, *, count: int = 1, **rest):
|
||||
super().__init__(**rest)
|
||||
self.count = count
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
txn = super().to_cmd_obj()
|
||||
txn = {
|
||||
**txn,
|
||||
'TransactionType': 'TicketCreate',
|
||||
'TicketCount': self.count,
|
||||
}
|
||||
return txn
|
||||
|
||||
|
||||
class SetHook(Transaction):
|
||||
'''A SetHook transaction for the experimental hook amendment'''
|
||||
def __init__(self,
|
||||
*,
|
||||
create_code: str,
|
||||
hook_on: str = '0000000000000000',
|
||||
**rest):
|
||||
super().__init__(**rest)
|
||||
self.create_code = create_code
|
||||
self.hook_on = hook_on
|
||||
|
||||
def to_cmd_obj(self) -> dict:
|
||||
txn = super().to_cmd_obj()
|
||||
txn = {
|
||||
**txn,
|
||||
'TransactionType': 'SetHook',
|
||||
'CreateCode': self.create_code,
|
||||
'HookOn': self.hook_on,
|
||||
}
|
||||
return txn
|
||||
@@ -1140,10 +1140,17 @@
|
||||
# The online delete process checks periodically
|
||||
# that rippled is still in sync with the network,
|
||||
# and that the validated ledger is less than
|
||||
# 'age_threshold_seconds' old. If not, then continue
|
||||
# sleeping for this number of seconds and
|
||||
# checking until healthy.
|
||||
# Default is 5.
|
||||
# 'age_threshold_seconds' old. By default, if it
|
||||
# is not the online delete process aborts and
|
||||
# tries again later. If 'recovery_wait_seconds'
|
||||
# is set and rippled is out of sync, but likely to
|
||||
# recover quickly, then online delete will wait
|
||||
# this number of seconds for rippled to get back
|
||||
# into sync before it aborts.
|
||||
# Set this value if the node is otherwise staying
|
||||
# in sync, or recovering quickly, but the online
|
||||
# delete process is unable to finish.
|
||||
# Default is unset.
|
||||
#
|
||||
# Optional keys for Cassandra:
|
||||
#
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
217
docs/sidechain/GettingStarted.md
Normal file
217
docs/sidechain/GettingStarted.md
Normal file
@@ -0,0 +1,217 @@
|
||||
## Introduction
|
||||
|
||||
This document walks through the steps to setup a side chain running on your local
|
||||
machine and make your first cross chain transfers.
|
||||
|
||||
## Get Ready
|
||||
|
||||
This section describes how to install the python dependencies, create the
|
||||
environment variables, and create the configuration files that scripts need to
|
||||
run correctly.
|
||||
|
||||
### Build rippled
|
||||
|
||||
Checkout the `sidechain` branch from the rippled repository, and follow the
|
||||
usual process to build rippled.
|
||||
|
||||
### Create a Python virtual environment and install dependencies
|
||||
|
||||
1. Check the current python version. The python scripts require python 3.8 or greater:
|
||||
```
|
||||
python3 --version
|
||||
```
|
||||
|
||||
2. Choose a directory to put the virtual environment. For example, `~/envs`.
|
||||
|
||||
3. Create this directory and cd to it:
|
||||
```
|
||||
$ mkdir ~/env
|
||||
$ cd ~/env
|
||||
```
|
||||
|
||||
4. Create a new python virtual environment and activate it. Here the new
|
||||
envrionment is called `sidechain`. Of course, you can choose whatever name
|
||||
you'd like:
|
||||
```
|
||||
$ python3 -m venv sidechain
|
||||
$ source ./sidechain/bin/activate
|
||||
```
|
||||
|
||||
5. Install the required python modules. Change directories to where the
|
||||
side chain branch is located and use pip3 to install the modules: Assuming the
|
||||
code is located in `~/projs/sidechain`, the following commands will do it:
|
||||
```
|
||||
cd ~/projs/sidechain
|
||||
$ pip3 install -r bin/sidechain/python/requirements.txt
|
||||
```
|
||||
|
||||
### Activate the python virtual environment
|
||||
|
||||
```
|
||||
$ cd ~/env
|
||||
$ source ./sidechain/bin/activate
|
||||
```
|
||||
|
||||
There's no harm if it was already active.
|
||||
|
||||
### Environment variables
|
||||
|
||||
The python scripts need to know the locations of two files and one directory.
|
||||
These can be specified either through command line arguments or by setting
|
||||
environment variables.
|
||||
|
||||
1. The location of the rippled executable used for main chain servers. Either
|
||||
set the environment variable `RIPPLED_MAINCHAIN_EXE` or use the command line
|
||||
switch `--exe_mainchain`. Until a new RPC is integrated into the main branch
|
||||
(this will happen very soon), use the code built from the sidechain branch as
|
||||
the main chain exe.
|
||||
2. The location of the rippled executable used for side chain servers. Either
|
||||
set the environment variable `RIPPLED_SIDECHAIN_EXE` or use the command line
|
||||
switch `--exe_sidechain`. This should be the rippled executable built from
|
||||
the sidechain branch.
|
||||
3. The location of the directory that has the rippled configuration files.
|
||||
Either set the environment variable `RIPPLED_SIDECHAIN_CFG_DIR` or use the
|
||||
command line switch `--cfgs_dir`. The configuration files do not exist yet.
|
||||
There is a script to create these for you. For now, just choose a location
|
||||
where the files should live and make sure that directory exists.
|
||||
|
||||
Setting environment variables can be very convient. For example, a small script
|
||||
can be sourced to set these environment variables when working with side chains.
|
||||
|
||||
|
||||
### Creating configuration files
|
||||
|
||||
Assuming rippled is built, the three environment variables are set, and the
|
||||
python environment is activated, run the following script:
|
||||
```
|
||||
bin/sidechain/python/create_config_files.py --usd
|
||||
```
|
||||
|
||||
There should now be many configuration files in the directory specified by the
|
||||
`RIPPLED_SIDECHAIN_CFG_DIR` environment variable. The `--usd` creates a sample
|
||||
cross chain assert for USD -> USD transfers.
|
||||
|
||||
## Running the interactive shell
|
||||
|
||||
There is an interactive shell called `RiplRepl` that can be used to explore
|
||||
side chains. It will use the configuration files built above to spin up test
|
||||
rippled main chain running in standalone mode as well as 5 side chain federators
|
||||
running in regular consensus mode.
|
||||
|
||||
To start the shell, run the following script:
|
||||
```
|
||||
bin/sidechain/python/riplrepl.py
|
||||
```
|
||||
|
||||
The shell will not start until the servers have synced. It may take a minute or
|
||||
two until they do sync. The script should give feedback while it is syncing.
|
||||
|
||||
Once the shell has started, the following message should appear:
|
||||
```
|
||||
Welcome to the sidechain test shell. Type help or ? to list commands.
|
||||
|
||||
RiplRepl>
|
||||
```
|
||||
|
||||
Type the command `server_info` to make sure the servers are running. An example output would be:
|
||||
```
|
||||
RiplRepl> server_info
|
||||
pid config running server_state ledger_seq complete_ledgers
|
||||
main 0 136206 main.no_shards.mainchain_0/rippled.cfg True proposing 75 2-75
|
||||
side 0 136230 sidechain_0/rippled.cfg True proposing 92 1-92
|
||||
1 136231 sidechain_1/rippled.cfg True proposing 92 1-92
|
||||
2 136232 sidechain_2/rippled.cfg True proposing 92 1-92
|
||||
3 136233 sidechain_3/rippled.cfg True proposing 92 1-92
|
||||
4 136234 sidechain_4/rippled.cfg True proposing 92 1-92
|
||||
```
|
||||
|
||||
Of course, you'll see slightly different output on your machine. The important
|
||||
thing to notice is there are two categories, one called `main` for the main chain
|
||||
and one called `side` for the side chain. There should be a single server for the
|
||||
main chain and five servers for the side chain.
|
||||
|
||||
Next, type the `balance` command, to see the balances of the accounts in the address book:
|
||||
```
|
||||
RiplRepl> balance
|
||||
balance currency peer limit
|
||||
account
|
||||
main root 99,999,989,999.999985 XRP
|
||||
door 9,999.999940 XRP
|
||||
side door 99,999,999,999.999954 XRP
|
||||
```
|
||||
|
||||
There are two accounts on the main chain: `root` and `door`; and one account on the side chain: `door`. These are not user accounts. Let's add two user accounts, one on the main chain called `alice` and one on the side chain called `bob`. The `new_account` command does this for us.
|
||||
|
||||
```
|
||||
RiplRepl> new_account mainchain alice
|
||||
RiplRepl> new_account sidechain bob
|
||||
```
|
||||
|
||||
This just added the accounts to the address book, but they don't exist on the
|
||||
ledger yet. To do that, we need to fund the accounts with a payment. For now,
|
||||
let's just fund the `alice` account and check the balances. The `pay` command
|
||||
makes a payment on one of the chains:
|
||||
|
||||
```
|
||||
RiplRepl> pay mainchain root alice 5000
|
||||
RiplRepl> balance
|
||||
balance currency peer limit
|
||||
account
|
||||
main root 99,999,984,999.999969 XRP
|
||||
door 9,999.999940 XRP
|
||||
alice 5,000.000000 XRP
|
||||
side door 99,999,999,999.999954 XRP
|
||||
bob 0.000000 XRP
|
||||
```
|
||||
|
||||
Finally, let's do something specific to side chains: make a cross chain payment.
|
||||
The `xchain` command makes a payment between chains:
|
||||
|
||||
```
|
||||
RiplRepl> xchain mainchain alice bob 4000
|
||||
RiplRepl> balance
|
||||
balance currency peer limit
|
||||
account
|
||||
main root 99,999,984,999.999969 XRP
|
||||
door 13,999.999940 XRP
|
||||
alice 999.999990 XRP
|
||||
side door 99,999,995,999.999863 XRP
|
||||
bob 4,000.000000 XRP
|
||||
```
|
||||
|
||||
Note: the account reserve on the side chain is 100 XRP. The cross chain amount
|
||||
must be greater than 100 XRP or the payment will fail.
|
||||
|
||||
Making a cross chain transaction from the side chain to the main chain is similar:
|
||||
```
|
||||
RiplRepl> xchain sidechain bob alice 2000
|
||||
RiplRepl> balance
|
||||
balance currency peer limit
|
||||
account
|
||||
main root 99,999,984,999.999969 XRP
|
||||
door 11,999.999840 XRP
|
||||
alice 2,999.999990 XRP
|
||||
side door 99,999,997,999.999863 XRP
|
||||
bob 1,999.999990 XRP
|
||||
```
|
||||
|
||||
If you typed `balance` very quickly, you may catch a cross chain payment in
|
||||
progress and the XRP may be deducted from bob's account before it is added to
|
||||
alice's. If this happens just wait a couple seconds and retry the command. Also
|
||||
note that accounts pay a ten drop fee when submitting transactions.
|
||||
|
||||
Finally, exit the program with the `quit` command:
|
||||
```
|
||||
RiplRepl> quit
|
||||
Thank you for using RiplRepl. Goodbye.
|
||||
|
||||
|
||||
WARNING: Server 0 is being stopped. RPC commands cannot be sent until this is restarted.
|
||||
```
|
||||
|
||||
Ignore the warning about the server being stopped.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Those two cross chain payments are a "hello world" for side chains. It makes sure
|
||||
you're environment is set up correctly.
|
||||
130
docs/sidechain/configFile.md
Normal file
130
docs/sidechain/configFile.md
Normal file
@@ -0,0 +1,130 @@
|
||||
## Introduction
|
||||
|
||||
The config file for side chain servers that run as federators require three
|
||||
addition configuration stanzas. One additional stanza is required if the
|
||||
federator will run in standalone mode, and one existing stanza (`ips_fixed`) can
|
||||
be useful if running a side chain network on the local machine.
|
||||
|
||||
## The `[sidechain]` stanza
|
||||
|
||||
This stanza defines the side chain top level parameters. This includes:
|
||||
* The federator's signing key. This is needed to add a signature to a
|
||||
mutli-signed transaction before submitting it on the main chain or the side
|
||||
chain.
|
||||
* The main chain account. This is the account controlled by the federators and
|
||||
the account users will send their assets to initiate cross chain transactions.
|
||||
Some documentation calls this the main chain "door" account.
|
||||
* The ip address and port of the main chain. This is needed to communicate with
|
||||
the main chain server.
|
||||
|
||||
An example stanza may look like this (where the "X" are part of a secret key):
|
||||
```
|
||||
[sidechain]
|
||||
signing_key=sXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
mainchain_account=rDj4pMuPv8gAD5ZvUrpHza3bn6QMAK6Zoo
|
||||
mainchain_ip=127.0.0.1
|
||||
mainchain_port_ws=6007
|
||||
```
|
||||
|
||||
## The `[sidechain_federators]` stanza
|
||||
|
||||
This stanza defines the signing public keys of the sidechain federators. This is
|
||||
needed to know which servers to collect transaction signatures from. An example
|
||||
stanza may look like this:
|
||||
|
||||
```
|
||||
[sidechain_federators]
|
||||
aKNmFC2QWXbCUFq9XxaLgz1Av6SY5ccE457zFjSoNwaFPGEwz6ab
|
||||
aKE9m7iDjhy5QAtnrmE8RVbY4RRvFY1Fn3AZ5NN2sB4N9EzQe82Z
|
||||
aKNFZ3L7Y7z8SdGVewkVuqMKmDr6bqmaErXBdWAVqv1cjgkt1X36
|
||||
aKEhTF5hRYDenn2Rb1NMza1vF9RswX8gxyJuuYmz6kpU5W6hc7zi
|
||||
aKEydZ5rmPm7oYQZi9uagk8fnbXz4gmx82WBTJcTVdgYWfRBo1Mf
|
||||
```
|
||||
|
||||
## The `[sidechain_assets]` and associated stanzas.
|
||||
|
||||
These stanza define what asset is used as the cross chain asset between the main
|
||||
chain and the side chain. The `mainchain_asset` is the asset that accounts on
|
||||
the main chain send to the account controlled by the federators to initiate an
|
||||
cross chain transaction. The `sidechain_asset` is the asset that will be sent to
|
||||
the destination address on the side chain. When returning an asset from the side
|
||||
chain to the main chain, the `sidechain_asset` is sent to the side chain account
|
||||
controlled by the federators and the `mainchain_asset` will be sent to the
|
||||
destination address on the main chain. There are amounts associated with these
|
||||
two assets. These amount define an exchange rate. If the value of the main chain
|
||||
asset is 1, and the amount of the side chain asset is 2, then for every asset
|
||||
locked on the main chain, twice of many assets are sent on the side chain.
|
||||
Similarly, for every asset returned from the main chain, half as many assets are
|
||||
sent on the main chain. The format used to specify these amounts is the same as
|
||||
used in json RPC commands.
|
||||
|
||||
There are also fields for "refund_penalty" on the main chain and side chain.
|
||||
This is the amount to deduct from refunds if a transaction fails. For example,
|
||||
if a cross chain transaction sends 1 XRP to an address on the side chain that
|
||||
doesn't exist (and the reserve is greater than 1 XRP), then a refund is issued
|
||||
on the main chain. If the `mainchain_refund_penalty` is 400 drops, then the
|
||||
amount returned is 1 XRP - 400 drops.
|
||||
|
||||
An example of stanzas where the main chain asset is XRP, and the sidechain asset
|
||||
is also XRP, and the exchange rate is 1 to 1 may look like this:
|
||||
|
||||
```
|
||||
[sidechain_assets]
|
||||
xrp_xrp_sidechain_asset
|
||||
|
||||
[xrp_xrp_sidechain_asset]
|
||||
mainchain_asset="1"
|
||||
sidechain_asset="1"
|
||||
mainchain_refund_penalty="400"
|
||||
sidechain_refund_penalty="400"
|
||||
```
|
||||
|
||||
|
||||
An example of stanzas where the main chain asset is USD/rD... and the side chain
|
||||
asset is USD/rHb... and the exchange rate is 1 to 2 may look like this:
|
||||
|
||||
```
|
||||
[sidechain_assets]
|
||||
iou_iou_sidechain_asset
|
||||
|
||||
[iou_iou_sidechain_asset]
|
||||
mainchain_asset={"currency": "USD", "issuer": "rDj4pMuPv8gAD5ZvUrpHza3bn6QMAK6Zoo", "value": "1"}
|
||||
sidechain_asset={"currency": "USD", "issuer": "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "value": "2"}
|
||||
mainchain_refund_penalty={"currency": "USD", "issuer": "rDj4pMuPv8gAD5ZvUrpHza3bn6QMAK6Zoo", "value": "0.02"}
|
||||
sidechain_refund_penalty={"currency": "USD", "issuer": "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", "value": "0.04"}
|
||||
```
|
||||
|
||||
|
||||
|
||||
## The `[sidechain_federators_secrets]` stanza
|
||||
|
||||
When running a side chain with a single federator in stand alone mode (useful
|
||||
for debugging), that single server needs to know the signing keys of all the
|
||||
federators in order to submit transactions. This stanza will not normally only
|
||||
be part of configuration files that are used for testing and debugging.
|
||||
|
||||
An example of a stanza with federator secrets may look like this (where the "X"
|
||||
are part of a secret key).
|
||||
|
||||
```
|
||||
[sidechain_federators_secrets]
|
||||
sXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
sXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
sXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
sXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
sXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||
```
|
||||
|
||||
## The `[ips_fixed]` stanza
|
||||
|
||||
When running a test net it can be useful to hard code the ip addresses of the
|
||||
side chain servers. An example of such a stanza used to run a test net locally
|
||||
may look like this:
|
||||
|
||||
```
|
||||
[ips_fixed]
|
||||
127.0.0.2 51238
|
||||
127.0.0.3 51239
|
||||
127.0.0.4 51240
|
||||
127.0.0.5 51241
|
||||
```
|
||||
823
docs/sidechain/design.md
Normal file
823
docs/sidechain/design.md
Normal file
@@ -0,0 +1,823 @@
|
||||
# Introduction
|
||||
|
||||
This document covers the design of side chains using the XRP ledger. It covers
|
||||
the implementation of federators, how federators are initially synced and kept
|
||||
in sync, how cross chain transactions work, and how errors are handled. It does
|
||||
not give a high level overview of side chains or describe their benefits.
|
||||
|
||||
# Terminology
|
||||
|
||||
_federator_: A server that listens for triggering transactions on both the main
|
||||
chain and the side chain. Each federator has a signing key associated with it
|
||||
that is used to sign transactions. A transaction must be signed by a quorum of
|
||||
federators before it can be submitted. Federators are responsible for creating
|
||||
and signing valid response transactions, collecting signatures from other
|
||||
federators, and submitting transactions to the main chain and side chain.
|
||||
|
||||
_main chain_: Ledger where assets originate and where assets will be locked
|
||||
while used on the side chain. For most applications, the main chain will be the
|
||||
XRP ledger mainnet.
|
||||
|
||||
_side chain_: Ledger where proxy assets for the locked main chain assets are
|
||||
issued. Side chains may have rules, transactors, and validators that are very
|
||||
different from the main chain. Proxy assets on the side chain can be sent back
|
||||
to the main chain where they will be be unlocked from the control of the
|
||||
federators.
|
||||
|
||||
_door account_: Account controlled by the federators. There are two door
|
||||
accounts: one on the main chain and one on the side chain. Cross chain
|
||||
transactions are started by users sending assets to a door account. Main chain
|
||||
to side chain transactions cause the balance to increase on the main chain door
|
||||
account and the balance to decrease on the side chain door account. It is called
|
||||
a "door" because it is the mechanism to move assets from one chain to another -
|
||||
much like going between rooms in a house requires stepping through a door.
|
||||
|
||||
_triggering transaction_: A transaction that causes the federators to start the
|
||||
process of signing and submitting a new response transaction. For example,
|
||||
sending XRP to the main chain's door account is a triggering transaction that
|
||||
will cause the federators to submit a new transaction on the side chain.
|
||||
|
||||
_response transaction_: A transaction submitted by the federators in reaction to
|
||||
a triggering transaction. Note that _triggering transaction_ and _response
|
||||
transaction_ depends on context. Sending XRP from a _door account_ to a user
|
||||
account is a _response transaction_ when thinking about cross chain
|
||||
transactions. It is a _triggering transaction_ when thinking about how to handle
|
||||
failed transactions.
|
||||
|
||||
# New RPC Command is a key primitive
|
||||
|
||||
Side chains introduce a new subscription stream called
|
||||
"account_history_tx_stream". Given an account, this streams both new
|
||||
transactions and historical transactions from validated ledgers back to the
|
||||
client. The transactions are streamed in order and without gaps, and each
|
||||
transaction is given a numeric id. New transactions start at id 0 and continue
|
||||
in the positive direction. Historical transaction start at id -1 and continue in
|
||||
the negative direction. New transactions are sent in the same order as they were
|
||||
applied to the ledger, and historical tranasations are in the reverse order they
|
||||
were applied to the ledger. The server will continue to stream historical
|
||||
transaction until it reaches the account's first transaction or the user sends a
|
||||
command signaling that historical transactions are no longer needed. This can be
|
||||
done without closing the stream, and new transactions will continue to be sent.
|
||||
Note that these transactions include all the transactions that effect the
|
||||
account, not just triggering and response transactions.
|
||||
|
||||
It's important to note that while historical and new transactions may be
|
||||
interleaved in the stream, there are never any gaps in the transactions.
|
||||
Transaction 7 MUST be sent before transaction 8, and transaction -7 MUST be sent
|
||||
before transaction -8.
|
||||
|
||||
This is the key primitive that allows federators to agree on transaction
|
||||
values - transaction types, sequence numbers, asset amounts, and destination
|
||||
addresses - without communicating amung themselves (of course signing
|
||||
transaction requires communication). Since the transactions are from validated
|
||||
ledgers, all the federators will see the same transactions in the same order.
|
||||
|
||||
# Federators
|
||||
|
||||
## Federator Introduction
|
||||
|
||||
A federator acts as a bridge between a main chain and a side chain. Through a
|
||||
multi-signature scheme, the federators collectively control an account on the
|
||||
main chain and an account on the side chain. These accounts are called door
|
||||
accounts. A federator listens for transactions on these door accounts. When a
|
||||
federator hears a triggering transaction, it will eventually submit a new
|
||||
response transaction that completes the triggering transaction.
|
||||
|
||||
Initially, the federators will live in the same executable as the side chain
|
||||
validators. However, the proposed implementation purposely does not take
|
||||
advantage of this fact. The motivation for this is:
|
||||
|
||||
1. It makes it easy to eventually separate out the federator implementation from
|
||||
side chain validators.
|
||||
2. The side chain to main chain transactions will be implemented the same way as
|
||||
the main chain to side chain transactions. Building and maintaining one
|
||||
implementation is preferable to maintaining two implementations.
|
||||
|
||||
## Keeping the federators in sync
|
||||
|
||||
Federators decide to sign transactions by using the "account_history_tx_stream"
|
||||
to listen for transactions on each chain. New transactions on the main chain
|
||||
will cause a federator to sign a transaction meant for the side chain.
|
||||
Similarly, new transactions on the side chain will cause a federator to sign a
|
||||
transaction meant for the main chain. As a concrete example, consider how XRP is
|
||||
locked on the main chain and distributed on a side chain. A user sends XRP to
|
||||
the main chain door account. This causes the federators to submit a transaction
|
||||
sending XRP to a destination on the side chain. Recall that a transaction that
|
||||
causes a federator to sign a transaction is called a triggering transaction, and
|
||||
a transaction created to handle a triggering transaction is called a response
|
||||
transaction. In the example above, the user sending XRP on the main chain is a
|
||||
triggering transaction and the tranasaction created by the federators and
|
||||
submitted on the side chain is a response transaction.
|
||||
|
||||
When a new triggering transaction is detected, a federator needs to create a
|
||||
response transaction. The fee, destination address, and amount are all known.
|
||||
The only value that isn't fixed or derived from the triggering transaction is
|
||||
the account sequence number. It is easy to agree on a sequence number. But first
|
||||
let's show that stream of triggering transactions are the same for all the
|
||||
validators.
|
||||
|
||||
Notice that a response transaction is always on the opposite chain as the
|
||||
corresponding triggering transaction. If a response transaction could be on
|
||||
either chain, then there would be timing issues. Consider what would happen if
|
||||
two triggering transaction came in, one from the main chain and one from the
|
||||
side chain, and both of these triggering transactions required response
|
||||
transactions on the main chain. Since there are separate transaction streams
|
||||
comming from the main chain and side chain, different federators may see these
|
||||
transaction arrive in different orders. However, since triggering and response
|
||||
transactions are on different chains, the federators don't need to deal with
|
||||
this case. (Note: there is at one response transaction that is needed in
|
||||
exceptional circumstances that violates this. Tickets are used to handle this
|
||||
transactions and will be described later).
|
||||
|
||||
Also notice that "account_history_tx_stream" delivers transactions in the order
|
||||
they were applied to the ledger without gaps.
|
||||
|
||||
This means that once a federator is in a state where it knows what sequence
|
||||
number should be used for the next response transaction (call it S), it will
|
||||
know the sequence number for all the subsequent response transactions. It will
|
||||
just be S+1, S+2, S+3, ect. Also notice that once in sync all the federators
|
||||
will see the same transactions in the same order. So all the federators will
|
||||
create the same response transactions and in the same order.
|
||||
|
||||
## Getting a federator in sync
|
||||
|
||||
When a federator joins the network, it doesn't know which triggering
|
||||
transactions it needs to sign and it doesn't know what sequence numbers should
|
||||
be used for response transactions. The "account_history_tx_stream" can be used
|
||||
to find this information and get the federator to a state where it can start
|
||||
signing and submitting transactions.
|
||||
|
||||
While getting into sync, a federator collects historical and new transactions
|
||||
from both the side chain and main chain. Each transaction has an id that is used
|
||||
to keep the transactions in the same order they were applied to the ledger, and
|
||||
the collections are kept in this order.
|
||||
|
||||
One piece of information a syncing federator needs to find is which triggering
|
||||
transactions need to be treated as new and which ones have already been handled.
|
||||
This is easily found by looking at the historical transaction from the
|
||||
"account_history_tx_stream". The first time a response transaction is found,
|
||||
the hash of associated triggering transaction is noted (this is be recorded as
|
||||
a memo in the response transaction). All the triggering transactions that
|
||||
precede the noted triggering transaction have already been handled. The
|
||||
"account_history_tx_stream" must continue to stream historical transactions at
|
||||
least until the first response transaction is found. For example, if the first
|
||||
observed response transaction on the main chain has hash `r_hash_mainchain`
|
||||
and associated triggering transaction of `t_hash_sidechain`, that means we know
|
||||
all the triggering transactions on the side chain before `t_hash_sidechain` have
|
||||
been handled (including `t_hash_sidechain`).
|
||||
|
||||
Another set of data that needs to be collected are all the historical
|
||||
triggering transactions that come after `t_hash` (see above). Of course,
|
||||
`t_hash` comes from the "account_history_tx_stream" from one chain, and the
|
||||
triggering transactions come from the other chain. This means more
|
||||
transactions than needed may be gathered.
|
||||
|
||||
Historical transaction continue to be streamed until the triggering transaction
|
||||
associated with `t_hash_this_chain` is found and value of `t_hash_other_chain`
|
||||
is found. For example, the main chain will continue to collect historical
|
||||
transaction until:
|
||||
|
||||
1) The side chain stream has found a response transaction and informed the main
|
||||
chain of the hash of the associated triggering transaction.
|
||||
|
||||
2) The side chain stream has found that triggering transaction.
|
||||
|
||||
3) This main chain stream has found a response transaction and informed the side
|
||||
chain syncing algorithm of the associated triggering transaction.
|
||||
|
||||
The above description does not handle the case where the start of histoical
|
||||
transactions is reached without finding any response transactions. If this
|
||||
happens then the other chain must also collect all the historical transactions,
|
||||
since we cannot show that triggering transaction has ever been handled.
|
||||
|
||||
Once this data has been collected, a command will be sent to ask the
|
||||
"account_history_tx_stream" to stop sending historical transaction (Note:
|
||||
without closing the stream. If the stream were closed it would be possible to
|
||||
miss a transaction). Starting from the transaction after the `t_hash`
|
||||
transaction, the collected triggering transaction will be iterated in the order
|
||||
they were applied to the ledger and treated as if they were newly arrived from
|
||||
the transaction stream. Once this is done the federator is synced and can switch
|
||||
to handling new transactions normally.
|
||||
|
||||
As long as there are regular cross chain transactions being sent from both the
|
||||
main chain and the side chain, the above procedure doesn't require too many
|
||||
historical transactions. However, if one chain almost never sends cross chain
|
||||
transactions then the syncing procedure is not as effiecient as it could be. As
|
||||
an extreme example, consider a main chain that sends cross chain transactions to
|
||||
a side chain, and the side chain never sends cross chain transactions back.
|
||||
Since there would be no response transactions on the main chain, the sync
|
||||
algorithm would fetch all of the main chain transactions. One way to improve
|
||||
this situation is for the federators to checkpoint the last known response
|
||||
transaction and its corresponding triggering transactions. If they did this
|
||||
individually, then on startup a federator would need to fetch at most as much
|
||||
history as the time it was down. If they did this as a group (by adding a new
|
||||
ledger object on the side chain, for example), then syncing could require much
|
||||
less history. For now, these strategies are not used. The benefits of a simplier
|
||||
implementations and not adding any new ledger objects outweighted the benefits
|
||||
of faster syncing for some types of sidechains.
|
||||
|
||||
## Federator Implementation
|
||||
|
||||
The Federator is an event loop that services events sent to it from the
|
||||
listeners. Events are handed in the `mainLoop` method. This runs on a separate
|
||||
thread. It runs on a separate thread so all the event handlers run on the order
|
||||
they were received on and on the same thread.
|
||||
|
||||
### Federator Events
|
||||
|
||||
A `Federator` event is a `std::variant` of all the event types. The current
|
||||
event types are:
|
||||
|
||||
* `XChainTransferDetected`. This is added when a federator detects the start of
|
||||
cross chain transaction.
|
||||
```c++
|
||||
struct XChainTransferDetected
|
||||
{
|
||||
// direction of the transfer
|
||||
Dir dir_;
|
||||
// Src account on the src chain
|
||||
AccountID src_;
|
||||
// Dst account on the dst chain
|
||||
AccountID dst_;
|
||||
STAmount deliveredAmt_;
|
||||
std::uint32_t txnSeq_;
|
||||
uint256 txnHash_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
};
|
||||
```
|
||||
|
||||
* `XChainTransferResult`. This is added when a federator detects the end of a
|
||||
cross chain transaction.
|
||||
```c++
|
||||
struct XChainTransferResult
|
||||
{
|
||||
// direction is the direction of the triggering transaction.
|
||||
// I.e. A "mainToSide" transfer result is a transaction that
|
||||
// happens on the sidechain (the triggering transaction happended on the
|
||||
// mainchain)
|
||||
Dir dir_;
|
||||
AccountID dst_;
|
||||
std::optional<STAmount> deliveredAmt_;
|
||||
std::uint32_t txnSeq_;
|
||||
// Txn hash of the initiating xchain transaction
|
||||
uint256 srcChainTxnHash_;
|
||||
// Txn has of the federator's transaction on the dst chain
|
||||
uint256 txnHash_;
|
||||
TER ter_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
};
|
||||
```
|
||||
|
||||
* `RefundTransferResult`. This is added when a federator detects the end of a
|
||||
refund transactions. Refunds may occur if there is an error transfering funds
|
||||
at the end of a cross chain transaction.
|
||||
```c++
|
||||
struct RefundTransferResult
|
||||
{
|
||||
// direction is the direction of the triggering transaction.
|
||||
// I.e. A "mainToSide" refund transfer result is a transaction that
|
||||
// happens on the mainchain (the triggering transaction happended on the
|
||||
// mainchain, the failed result happened on the side chain, and the refund
|
||||
// result happened on the mainchain)
|
||||
Dir dir_;
|
||||
AccountID dst_;
|
||||
std::optional<STAmount> deliveredAmt_;
|
||||
std::uint32_t txnSeq_;
|
||||
// Txn hash of the initiating xchain transaction
|
||||
uint256 srcChainTxnHash_;
|
||||
// Txn hash of the federator's transaction on the dst chain
|
||||
uint256 dstChainTxnHash_;
|
||||
// Txn hash of the refund result
|
||||
uint256 txnHash_;
|
||||
TER ter_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
};
|
||||
```
|
||||
|
||||
* `TicketCreateResult`. This is added when the federator detects a ticket create
|
||||
transaction.
|
||||
|
||||
```
|
||||
struct TicketCreateResult
|
||||
{
|
||||
Dir dir_;
|
||||
bool success_;
|
||||
std::uint32_t txnSeq_;
|
||||
std::uint32_t ledgerIndex_;
|
||||
uint256 srcChainTxnHash_;
|
||||
uint256 txnHash_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
std::uint32_t sourceTag_;
|
||||
std::string memoStr_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
|
||||
void
|
||||
removeTrigger();
|
||||
};
|
||||
```
|
||||
|
||||
* `DepositAuthResult`. This is added when the federator detects a deposit auth
|
||||
transaction. Deposit auth is used to pause cross chain transactions if the
|
||||
federators fall too far behind.
|
||||
```
|
||||
struct DepositAuthResult
|
||||
{
|
||||
Dir dir_;
|
||||
bool success_;
|
||||
std::uint32_t txnSeq_;
|
||||
std::uint32_t ledgerIndex_;
|
||||
uint256 srcChainTxnHash_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
AccountFlagOp op_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
};
|
||||
```
|
||||
|
||||
* `BootstrapTicket`. This is added when the federator detects one of the initial
|
||||
ticket transactions that is added during account setup.
|
||||
```
|
||||
struct BootstrapTicket
|
||||
{
|
||||
bool isMainchain_;
|
||||
bool success_;
|
||||
std::uint32_t txnSeq_;
|
||||
std::uint32_t ledgerIndex_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
std::uint32_t sourceTag_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
};
|
||||
```
|
||||
|
||||
* `DisableMasterKeyResult`. This is added when the federator detects an
|
||||
`AccountSet` transaction that disables the master key. Transactions that come
|
||||
before this are assumed to be part of account setup.
|
||||
```
|
||||
struct DisableMasterKeyResult
|
||||
{
|
||||
bool isMainchain_;
|
||||
std::uint32_t txnSeq_;
|
||||
std::int32_t rpcOrder_;
|
||||
|
||||
EventType
|
||||
eventType() const;
|
||||
|
||||
Json::Value
|
||||
toJson() const;
|
||||
};
|
||||
```
|
||||
|
||||
* `HeartbeatTimer`. This is added at regular intervals and is used to trigger
|
||||
evants based on timeouts.
|
||||
|
||||
### Federator Event Handling
|
||||
|
||||
Handling the events is very simple. The `mainLoop` pops events off the event
|
||||
queue and dispatches it to an event handler. There is one event handler for each
|
||||
event type. There is also some logic to prevent busy waiting.
|
||||
|
||||
```c++
|
||||
void
|
||||
onEvent(event::XChainTransferDetected const& e);
|
||||
void
|
||||
onEvent(event::XChainTransferResult const& e);
|
||||
void
|
||||
onEvent(event::RefundTransferResult const& e);
|
||||
void
|
||||
onEvent(event::HeartbeatTimer const& e);
|
||||
|
||||
void
|
||||
Federator::mainLoop()
|
||||
{
|
||||
FederatorEvent event;
|
||||
while (!requestStop_)
|
||||
{
|
||||
if (!events_.pop(event))
|
||||
{
|
||||
using namespace std::chrono_literals;
|
||||
// In rare cases, an event may be pushed and the condition
|
||||
// variable signaled before the condition variable is waited on.
|
||||
// To handle this, set a timeout on the wait.
|
||||
std::unique_lock l{m_};
|
||||
cv_.wait_for(
|
||||
l, 1s, [this] { return requestStop_ || !events_.empty(); });
|
||||
continue;
|
||||
}
|
||||
std::visit([this](auto&& e) { this->onEvent(e); }, event);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Events are added to a queue in the `push` method.
|
||||
```c++
|
||||
void
|
||||
Federator::push(FederatorEvent const& e)
|
||||
{
|
||||
bool const notify = events_.empty();
|
||||
events_.push(e);
|
||||
if (notify)
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_);
|
||||
cv_.notify_one();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Due the threading and lifetime issues, `Federator` is kept as a `shared_ptr`
|
||||
inside of the app and enables `shared_from_this`. Since `shared_from_this`
|
||||
cannot be used from a constructor, it uses two-phase initialization of a
|
||||
constructor and an `init` function. These constructors are private, and objects
|
||||
are created with a `make_federator` function that implements the two-phase
|
||||
initialization. (Note: since `make_shared` cannot call a private constructor, a
|
||||
private `PrivateTag` is used instead.)
|
||||
|
||||
### Federator Listeners
|
||||
|
||||
There are two listener classes: a `MainchainListener` and a `SidechainListener`
|
||||
(both inherit from a common `ChainListener` class where much of the
|
||||
implementation lives). These classes monitor the chains for transactions on the
|
||||
door accounts and add the appropriate event to the federator. The
|
||||
`MainchainListener` uses a websocket to monitor transactions. Since the
|
||||
federator lives in the same executable as the side chain validators,
|
||||
`SidechainListener` used `InfoSub` directly rather than a websocket.
|
||||
|
||||
The federator is kept as `weak_ptr` in this class. Since these class will be used
|
||||
as part of a callback from different threads, both listener classes enable
|
||||
`shared_from_this`.
|
||||
|
||||
### Federator WebsocketClient
|
||||
|
||||
The `WebsocketClient` class takes an asio `io_service`, main chain server ip and
|
||||
port, and callback. When a command response or new stream result is received,
|
||||
the callback is executed (is will be called from the `io_service` thread). The
|
||||
`MainchainListener` uses this class to listen for transactions.
|
||||
This class is also be used to send transactions to the main chain.
|
||||
```c++
|
||||
WebsocketClient(
|
||||
std::function<void(Json::Value const&)> callback,
|
||||
boost::asio::io_service& ios,
|
||||
boost::asio::ip::address const& ip,
|
||||
std::uint16_t port,
|
||||
std::unordered_map<std::string, std::string> const& headers = {});
|
||||
```
|
||||
|
||||
# Triggering Transaction Handler
|
||||
|
||||
The triggering transaction handler is part of a single-threaded event loop that
|
||||
responds to events triggered from the different chains. It is single-threaded so
|
||||
there's no danger of events being processed out-of-order and for simplicity of
|
||||
code. Note that event handlers are not computationally intensive, so there would
|
||||
be little benefit to multiple threads.
|
||||
|
||||
When a new event is handled, a response transaction may be prepared. Apart from
|
||||
the sequence number, all the values of a response transaction can be determined
|
||||
from the trigging transaction, and it does not require communicating with the
|
||||
other federators. For example, when sending assets between chains, the response
|
||||
transaction will contain an amount equal to the XRP `delivered_amt` in the
|
||||
triggering transaction, a fixed fee, and a memo with the hash of the cross chain
|
||||
transaction. The memo is important because it creates a transaction unique to
|
||||
the triggering cross chain transaction, and it safer to sign such a transaction
|
||||
in case sequence numbers somehow get out of sync between the federators. The
|
||||
`LastLedgerSequence` field is not be set.
|
||||
|
||||
Next the federator will sign these transactions and send its signature to its
|
||||
peers. This happens in another thread so the event loop isn't slowed down.
|
||||
|
||||
Next the federator adds its signatures to the txn in the `pending transactions`
|
||||
collection for the appropriate chain. See [Adding a signature to Pending
|
||||
Transactions](#adding-a-signature-to-pending-transactions)
|
||||
|
||||
If it doesn't have enough signatures to complete the multi-signature, the
|
||||
federator will add signatures by listening for signature messages from other
|
||||
peers see the [Collecting Signatures](#collecting-signatures) section.
|
||||
|
||||
## Collecting Signatures
|
||||
|
||||
A federator receives signatures by listening to peer messages. Signatures are
|
||||
automatically sent when a federator detects a new cross chain transaction.
|
||||
|
||||
When a federator receives a new signature, it forwards it to its peers that have
|
||||
not already received this signature from this federator.
|
||||
|
||||
Next it checks if this transaction has already been handled. If so, it does
|
||||
nothing further.
|
||||
|
||||
Next the federator adds the signature to the txn in the `pending transactions`
|
||||
collection. See [Adding a signature to Pending
|
||||
Transactions](#adding-a-signature-to-pending-transactions).
|
||||
|
||||
Note that a federator may receive multiple signatures for the same transaction
|
||||
but with different sequence numbers. This should only happen if a federator
|
||||
somehow has the wrong sequence number and is later corrected.
|
||||
|
||||
## Adding a signature to Pending Transactions
|
||||
|
||||
The `pending transactions` collections stores the transactions that do not yet
|
||||
have enough signatures to be submitted or have not been confirmed as sent. There
|
||||
is one collection for the main chain and one for the side chain. The key to this
|
||||
collection is a hash of the triggering transaction, but with a sequence of zero
|
||||
and a fee of zero (remember that this transaction has a memo field with the hash
|
||||
of the cross chain transaction, so it is unique). It is hashed this way to
|
||||
detect inconsistent sequence numbers and fees. The `value` of this collection is
|
||||
a struct that contains this federators signature (if available) and another map
|
||||
with a `key` of sequence number and fee, and a `value` of a collection of
|
||||
signatures. Before adding a signature to this collection, if the signature is
|
||||
not on the multi-signature list, it is discarded. The signature is also checked
|
||||
for validity. If it is invalid, it is discarded.
|
||||
|
||||
After adding a signature to this collection it checks if it this signature is
|
||||
for a transaction with the same sequence number and fee as this federator, and
|
||||
if has enough signatures for a valid multi-signed transaction. If so, the
|
||||
transactions are added to the `queued transactions` collection for the
|
||||
appropriate chain and the function to submit transactions is called (see
|
||||
[Transaction Submit](#transaction-submit)).
|
||||
|
||||
If the transaction has enough signature for a valid multi-signed transaction,
|
||||
and the sequence and fee _do not_ match the ones from this federator, then this
|
||||
federator sequence number must be out of sync with the rest of the network. If
|
||||
it is detected, the federator will correct its sequence number. Note that there
|
||||
may be other transactions that have been submitted since this transaction, so
|
||||
the sequence number needs to be appropriately adjusted to account for this.
|
||||
Inconsistent fee will not be handled in the prototype. The fee will always be a
|
||||
constant. This federator will also change its signature for this transaction and
|
||||
submit it to the network (see [Transaction Submit](#transaction-submit)). This
|
||||
new signature will be broadcast to the network.
|
||||
|
||||
A heartbeat timer event will periodically check the collection for transactions
|
||||
in the queue older than some threshold. When these are detected, a error will be
|
||||
printed to the log. If the federator knows the transaction has already been
|
||||
handled by the network, it will be removed from the queue.
|
||||
|
||||
## Transaction Submit
|
||||
|
||||
There is a limit on the number of transaction in flight at any time. While the
|
||||
number of transactions is below this limit, and the next transaction in the
|
||||
sequence is part of the `queued transactions` collection, send the response
|
||||
transaction to the appropriate chain. Once a transaction is sent, it is removed
|
||||
from the `queued transactions` collection. However, it remains part of the
|
||||
`pending transactions` collection until a response transaction result is
|
||||
observed.
|
||||
|
||||
Note that limiting the number of transactions in flight to one makes for a
|
||||
simpler design, but greatly limits the throughput of cross-chain transactions.
|
||||
|
||||
## Handling Response Transaction Results
|
||||
|
||||
Response transaction results are used to know when a response transaction has
|
||||
been handled and can be removed from the `pending transactions` collection. It
|
||||
is also used to issue refunds when a response transaction fails under some
|
||||
circumstances.
|
||||
|
||||
If a transaction is fails is anything other than `tefAlready`, then a new
|
||||
response transaction is created that refunds some protion of the origional
|
||||
amount to the origional sending account. Gathering signatures for this refund
|
||||
transaction is the same as what's done other triggering transactions. Much like
|
||||
sending an asset cross-chain, transactions that trigger refunds and their
|
||||
response transations happen on different chains. This means we can use the same
|
||||
algorithm to assign sequence numbers to the response transaction.
|
||||
|
||||
If a transaction fails with a `tefAlready`, that means another federator already
|
||||
submitted the transaction. Ignore this error.
|
||||
|
||||
There is also a timer that checks for transactions that have not had results for
|
||||
too long of a time. If they are detected, an error is logged, but the prototype
|
||||
does not attempt to handle the error further.
|
||||
|
||||
## Assigning sequence numbers
|
||||
|
||||
A federator keeps a variable that gives the next sequence number to assign to a
|
||||
response transaction. When a new triggering transaction is detected, this
|
||||
sequence number is given to the response transaction and incremented. How the
|
||||
initial value is assigned is described in the [Getting a federator in
|
||||
sync](#getting-a-federator-in-sync) section. How an incorrect sequence number is
|
||||
corrected is described in the [Adding a signature to Pending
|
||||
Transactions](#adding-a-signature-to-pending-transactions) section.
|
||||
|
||||
## Assigning fees
|
||||
|
||||
Side chain fees are burned, so this balance can never be redeemed through normal
|
||||
cross chain transactions. If we wanted, these burned fees could be made
|
||||
available to the federators by withdrawing XRP from the main chain account.
|
||||
|
||||
Given these fees are burned and are (in effect) payed by the account doing a
|
||||
cross chain transaction, I propose these fees should be set on startup and kept
|
||||
constant. Initial implementations will use a 20 drop fee.
|
||||
|
||||
## Specifying a cross-chain destination address
|
||||
|
||||
When sending a cross chain payment, the destination on the originating chain is
|
||||
the special "door" account controlled by the federators. How does the user
|
||||
specify what the destination address on the side chain should be? There are two
|
||||
ways:
|
||||
|
||||
1) Specify the destination as a memo.
|
||||
2) Assign tags to destinations.
|
||||
|
||||
The memo field can always be used to specify a destination. In addition, when a
|
||||
new account is created, a new mapping is assigned between a tag and an address.
|
||||
With a main to side transaction, the new tag will map to the newly created side
|
||||
chain account.
|
||||
|
||||
The "tags" scheme is not yet designed. For now, the implementation will always
|
||||
use the memo field to specify the destination address.
|
||||
|
||||
If an account sends an asset to the door account without specifying an address, a
|
||||
refund will be issued to the sending account.
|
||||
|
||||
## Setting up the door accounts
|
||||
|
||||
The root account on the side chain is used as the door account. The door account
|
||||
on the main chain is just a regular account. The following transactions must be
|
||||
sent to these accounts before a running the federators:
|
||||
|
||||
* `SignerListSet`: Since the federators will jointly control these accounts, a
|
||||
`SignerListSet` transaction must be sent to both the main chain account and
|
||||
the side chain account. The signer list should consist of the federator's
|
||||
public signing keys and should match the keys specified in the config file.
|
||||
The quorum should be set to 80% of the federators on the list (i.e. for five
|
||||
federators, set this to 4).
|
||||
The federators use tickets to handle unusual situations. For example, if the
|
||||
federators fall too far behind they will disallow new cross chain transactions
|
||||
until they catch up. Three tickets are needed, and three transactions are needed
|
||||
to create the tickets (since they use the source tag as a way to set the purpose
|
||||
for the ticket).
|
||||
|
||||
* `Ticket`: Sent a `Ticket` transaction with the source tag of `1` to both the
|
||||
main chain account and side chain account.
|
||||
|
||||
* `Ticket`: Sent a `Ticket` transaction with the source tag of `2` to both the
|
||||
main chain account and side chain account.
|
||||
|
||||
* `Ticket`: Sent a `Ticket` transaction with the source tag of `3` to both the
|
||||
main chain account and side chain account.
|
||||
|
||||
* `TrustSet` if the cross chain transactions involve issued assets (IOUs), set
|
||||
up the trust lines by sending a `TrustSet` transaction to the appropriate
|
||||
accounts. If the cross chain transactions only involve XRP, this is not
|
||||
needed.
|
||||
|
||||
* `AccountSet`: Disable the master key with an `AccountSet` transactions. This
|
||||
ensures that nothing except the federators (as a group) control these
|
||||
accounts. Send this transaction to both the main chain account and side chain
|
||||
account.
|
||||
|
||||
*Important*: The `AccountSet` transaction that disables the master key *must* be
|
||||
the last transaction. The federator's initialization code uses this to
|
||||
distinguish transactions that are part of setup and other transactions.
|
||||
|
||||
## Handling a crashed main chain server
|
||||
|
||||
The side chain depends on a websocket to main chain server to listen for
|
||||
transactions. If the main chain server disconnects from the side chain a
|
||||
fail-over option should be added. This would allow a federator to automatically
|
||||
connect to other main chain servers if the one it is currency connected to goes
|
||||
down.
|
||||
|
||||
## Federator throughput
|
||||
|
||||
On average, federators must process cross chain transactions faster than they
|
||||
occur. If there are 10 cross chain transactions per ledger, but the federators
|
||||
can only sign and submit 5 response transactions per ledger, the federators will
|
||||
keep falling father behind and will never catch up. Monitoring the size of the
|
||||
queues can detect this situation, but there is no good remedy for it. The rate
|
||||
of cross chain transactions are out of it's control.
|
||||
|
||||
If this situation occurs, new transactions to the door account will be disabled
|
||||
with a "deposit auth" transaction, and transactions will be disabled until the
|
||||
federators catch up. Because this transaction is not in response to a triggering
|
||||
transaction on the "opposite" chain, assigning a sequence number for the
|
||||
"deposit auth" transaction is more involved. We use the protocol
|
||||
in [Handling an unordered event](#Handling-an-unordered-event) section to submit
|
||||
the transaction.
|
||||
|
||||
## Handling an unordered event
|
||||
|
||||
Cross chain payment transactions from one chain are sorted by that chain's
|
||||
consensus protocol. Each transaction results in one payment transaction in the
|
||||
destination chain, hence consuming one sequence number of the door account in
|
||||
the destination chain. Staring from the same initial sequence number assigned
|
||||
when the account was created, and processing the same stream of payment
|
||||
transactions, the federators agree on which sequence number to use for a given
|
||||
payment transaction without communication.
|
||||
|
||||
From time to time, however, federators have to create transactions to process
|
||||
unordered events, such as temporarily "disable" a door account with a "deposit
|
||||
auth" AccountSet transaction, or update the door accounts signerLists with
|
||||
SignerListSet transactions. Assigning sequence number to these transactions are
|
||||
more involved than payment transactions, because these events are not sorted
|
||||
with themselves nor with payment transactions. Since they are not sorted, there
|
||||
is a chance that different federators use different sequence numbers. If
|
||||
different sequence numbers were used for a transaction, this transaction and
|
||||
(depending on the design) some transactions following it won't be processed. So
|
||||
for these transactions, tickets are used to assign sequence numbers. Tickets are
|
||||
reserved when the side chain first starts (on genesis), and tickets are
|
||||
replenished as they are used.
|
||||
|
||||
Our first ticket based protocol used tickets for both the transaction that
|
||||
handles an unordered event and the "TicketCreate" transaction to create new
|
||||
tickets. It was simple but had two issues: the sequence numbers allocated to
|
||||
renewed tickets and the sequence numbers used for payment transactions occurred
|
||||
at the same time may overlap so the payment transactions must be modified,
|
||||
resigned and resubmitted; there is also a small chance that the payment
|
||||
transactions are delivered to the destination chain out of order. Our current
|
||||
design grows from the first design. We use a pre-allocated ticket pair, one main
|
||||
chain ticket and one side chain ticket, to submit "no-op" transactions to both
|
||||
chains. Once they are processed by the chains' consensus and sorted with payment
|
||||
transactions, in later rounds of the protocol, both the "TicketCreate"
|
||||
transactions to create new tickets and the transaction(s) that handles an
|
||||
unordered event will use real sequence numbers instead of tickets. Hence we
|
||||
avoid both the issues of the first design. The current design is shown in the
|
||||
diagram below.
|
||||
|
||||
The top portion of the diagram shows (simplified) payment process sequence. Note
|
||||
that the only usage of the side chain sequence numbers is for processing
|
||||
payments already sorted by main chain consensus, and vice versa. The bottom
|
||||
portion of the diagram shows the 3-round protocol for processing unordered
|
||||
events (round 2 and 3 could be merged). Note that the side chain sequence
|
||||
numbers still have a single usage, i.e. processing transactions already sorted
|
||||
by main chain consensus, and vice versa.
|
||||
|
||||
In more detail, the first round of the protocol uses a ticket pair to send no-op
|
||||
transactions to both of the chains. In the second round, the inclusion of the
|
||||
no-op transactions in the ledgers means they are sorted together with other
|
||||
transactions. Since they are sorted, the sequence numbers of their corresponding
|
||||
next round transactions (TicketCreate) are agreed by the federators. The
|
||||
federators can also predict the ticket numbers that will be allocated once the
|
||||
ticketCreate transactions are processed by the consensus. Hence they will not
|
||||
use those sequence numbers for other purposes. In the final round of the
|
||||
protocol, the new tickets are indeed created and the ticket pair are refilled,
|
||||
and the transaction(s) that handles the unordered event can take a sequence
|
||||
number and submit to its destination chain.
|
||||
|
||||
This protocol can be used for one-sided events such as "disable" main chain
|
||||
account temporarily, or two-sided events such as update the signerLists of both
|
||||
door accounts. To avoid a race resulted from multiple events compete the same
|
||||
ticket pair, every ticket pair has a "purpose" so that the pair can only be used
|
||||
for one type of events. Currently three purposes are implemented, or planned.
|
||||
|
||||

|
||||
|
||||
## Federator as a separate program
|
||||
|
||||
For the prototype, the federators will be validators on the side chain. However,
|
||||
a federator can be independent from both chains. The federator can listen for
|
||||
side chain transactions with a websocket, just like it does for the main chain.
|
||||
The `last submitted txn` and `last confirmed txn` values can be kept by the
|
||||
federators themselves.
|
||||
|
||||
The biggest advantage to combining a federator and a validator is to re-use the
|
||||
overlay layer. This saves on implementation time in the prototype. Longer term,
|
||||
it makes sense to separate a federator and a validator.
|
||||
|
||||
# Config file changes
|
||||
|
||||
See [this](configFile.md) document for the config file stanzas used to support
|
||||
side chains.
|
||||
|
||||
# New ledger objects
|
||||
|
||||
Notice that side chains do not require any new ledger objects, and do not
|
||||
require federators to communicate in order to agree on transaction values.
|
||||
|
||||
# New RPC commands
|
||||
|
||||
* "account_history_tx_stream" is used to get historic transactions
|
||||
when syncing and get new transactions once synced.
|
||||
|
||||
* "Federator info" is used to get information about the state of a federator,
|
||||
including its sync state and the state of its transaction queues.
|
||||
50
docs/sidechain/federatorAccountSetup.md
Normal file
50
docs/sidechain/federatorAccountSetup.md
Normal file
@@ -0,0 +1,50 @@
|
||||
## Introduction
|
||||
|
||||
Side chain federators work by controlling an account on the main chain and an
|
||||
account on the side chain. The account on the side chain is the root account.
|
||||
The account on the main chain is specified in the configuration file (See
|
||||
[configFile.md](docs/sidechain/configFile.md) for the new configuration file
|
||||
stanzas).
|
||||
|
||||
The test scripts will set up these accounts for you when running a test network
|
||||
on your local machine (see the functions `setup_mainchain` and `setup_sidechain`
|
||||
in the sidechain.py module). This document describes what's needed to set up
|
||||
these accounts if not using the scripts.
|
||||
|
||||
## Transactions
|
||||
|
||||
* `SignerListSet`: Since the federators will jointly control these accounts, a
|
||||
`SignerListSet` transaction must be sent to both the main chain account and
|
||||
the side chain account. The signer list should consist of the federator's
|
||||
public signing keys and should match the keys specified in the config file.
|
||||
The quorum should be set to 80% of the federators on the list (i.e. for five
|
||||
federators, set this to 4).
|
||||
|
||||
The federators use tickets to handle unusual situations. For example, if the
|
||||
federators fall too far behind they will disallow new cross chain transactions
|
||||
until they catch up. Three tickets are needed, and three transactions are needed
|
||||
to create the tickets (since they use the source tag as a way to set the purpose
|
||||
for the ticket).
|
||||
|
||||
* `Ticket`: Sent a `Ticket` transaction with the source tag of `1` to both the
|
||||
main chain account and side chain account.
|
||||
|
||||
* `Ticket`: Sent a `Ticket` transaction with the source tag of `2` to both the
|
||||
main chain account and side chain account.
|
||||
|
||||
* `Ticket`: Sent a `Ticket` transaction with the source tag of `3` to both the
|
||||
main chain account and side chain account.
|
||||
|
||||
* `TrustSet` if the cross chain transactions involve issued assets (IOUs), set
|
||||
up the trust lines by sending a `TrustSet` transaction to the appropriate
|
||||
accounts. If the cross chain transactions only involve XRP, this is not
|
||||
needed.
|
||||
|
||||
* `AccountSet`: Disable the master key with an `AccountSet` transactions. This
|
||||
ensures that nothing except the federators (as a group) control these
|
||||
accounts. Send this transaction to both the main chain account and side chain
|
||||
account.
|
||||
|
||||
*Important*: The `AccountSet` transaction that disables the master key *must* be
|
||||
the last transaction. The federator's initialization code uses this to
|
||||
distinguish transactions that are part of setup and other transactions.
|
||||
BIN
docs/sidechain/ticketsAndSeq.png
Normal file
BIN
docs/sidechain/ticketsAndSeq.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 182 KiB |
76
docs/sidechain/ticketsAndSeq.puml
Normal file
76
docs/sidechain/ticketsAndSeq.puml
Normal file
@@ -0,0 +1,76 @@
|
||||
@startuml
|
||||
|
||||
participant "main chain network" as mc #LightGreen
|
||||
box "Federator"
|
||||
participant "**main** chain\ndoor account listener" as mdl
|
||||
participant "**main** chain\nsignature collector" as msc
|
||||
participant "**main** chain\nsequence number" as msn #LightBlue
|
||||
participant "ticket pair" as t #LightBlue
|
||||
participant "unordered event" as ue #LightCoral
|
||||
participant "**side** chain\nsequence number" as ssn #LightBlue
|
||||
participant "**side** chain\nsignature collector" as ssc
|
||||
participant "**side** chain\ndoor account listener" as sdl
|
||||
end box
|
||||
participant "side chain network" as sc #LightGreen
|
||||
actor "federator admin" as fa #LightGreen
|
||||
|
||||
== payments ==
|
||||
group cross chain payment to side chain
|
||||
mc -> mdl: payment tx to door account\nin ledger
|
||||
mdl -> ssn: side chain door account payment tx created
|
||||
ssn -> ssc: sequence number filled
|
||||
ssc -> ssc: payment tx signed,\ncollect signatures
|
||||
ssc -> sc : with quorum signatures\nsubmit tx to network
|
||||
end
|
||||
group cross chain payment to main chain
|
||||
sc -> sdl: payment tx to door account\nin ledger
|
||||
sdl -> msn: main chain door account payment tx created
|
||||
msn -> msc: sequence number filled
|
||||
msc -> msc: payment tx signed,\ncollect signatures
|
||||
msc -> mc : with quorum signatures\nsubmit tx to network
|
||||
end
|
||||
|
||||
== unordered events ==
|
||||
group round 1
|
||||
fa -> ue : misc request from admin\nor federator internal event\nE.g. close main chain door account due to high load
|
||||
ue -> t : **two** no-op AccountSet txns created\n(for trigger ticketCreate txns round 2)
|
||||
activate t
|
||||
t -> msc: ticket number filled
|
||||
t -> ssc: ticket number filled
|
||||
deactivate t
|
||||
msc -> msc: no-op AccountSet tx signed,\ncollect signatures
|
||||
ssc -> ssc: no-op AccountSet tx signed,\ncollect signatures
|
||||
msc -> mc : with quorum signatures\nsubmit tx to network
|
||||
ssc -> sc : with quorum signatures\nsubmit tx to network
|
||||
end
|
||||
|
||||
group round 2
|
||||
'== unordered event, round 2 ==
|
||||
mc -> mdl: no-op AccountSet in ledger
|
||||
sc -> sdl: no-op AccountSet in ledger
|
||||
mdl -> ssn: create side chain door account ticketCreate tx\nto allocate side chain door account ticket\nto refill ticket pair
|
||||
sdl -> msn: create main chain door account ticketCreate tx\nto allocate main chain door account ticket\nto refill ticket pair
|
||||
ssn -> ssc: sequence number filled
|
||||
msn -> msc: sequence number filled
|
||||
ssc -> ssc: ticketCreate tx signed,\ncollect signatures
|
||||
msc -> msc: ticketCreate tx signed,\ncollect signatures
|
||||
ssc -> sc : with quorum signatures\nsubmit tx to network
|
||||
msc -> mc : with quorum signatures\nsubmit tx to network
|
||||
end
|
||||
|
||||
group round 3
|
||||
'== unordered event, round 3 ==
|
||||
mc -> mdl: ticketCreate in ledger
|
||||
mdl -> t : refill
|
||||
sc -> sdl: ticketCreate in ledger
|
||||
activate sdl
|
||||
sdl -> t : refill
|
||||
sdl -> msn: main chain deposit-auth AccountSet created
|
||||
note left: assuming the unordered event is to\nclose main chain door account\nto block new payments temporarily
|
||||
deactivate sdl
|
||||
msn -> msc: sequence number filled
|
||||
msc -> msc: deposit-auth AccountSet tx signed,\ncollect signatures
|
||||
msc -> mc : with quorum signatures\nsubmit tx to network
|
||||
end
|
||||
|
||||
@enduml
|
||||
@@ -632,7 +632,7 @@ RCLConsensus::Adaptor::doAccept(
|
||||
auto const lastVal = ledgerMaster_.getValidatedLedger();
|
||||
std::optional<Rules> rules;
|
||||
if (lastVal)
|
||||
rules = makeRulesGivenLedger(*lastVal, app_.config().features);
|
||||
rules.emplace(*lastVal, app_.config().features);
|
||||
else
|
||||
rules.emplace(app_.config().features);
|
||||
app_.openLedger().accept(
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
|
||||
#include <ripple/app/ledger/AcceptedLedger.h>
|
||||
#include <ripple/app/main/Application.h>
|
||||
#include <algorithm>
|
||||
#include <ripple/basics/Log.h>
|
||||
#include <ripple/basics/chrono.h>
|
||||
|
||||
namespace ripple {
|
||||
|
||||
@@ -28,34 +29,29 @@ AcceptedLedger::AcceptedLedger(
|
||||
Application& app)
|
||||
: mLedger(ledger)
|
||||
{
|
||||
transactions_.reserve(256);
|
||||
|
||||
auto insertAll = [&](auto const& txns) {
|
||||
auto const& idcache = app.accountIDCache();
|
||||
|
||||
for (auto const& item : txns)
|
||||
transactions_.emplace_back(std::make_unique<AcceptedLedgerTx>(
|
||||
ledger, item.first, item.second, idcache));
|
||||
{
|
||||
insert(std::make_shared<AcceptedLedgerTx>(
|
||||
ledger,
|
||||
item.first,
|
||||
item.second,
|
||||
app.accountIDCache(),
|
||||
app.logs()));
|
||||
}
|
||||
};
|
||||
|
||||
if (app.config().reporting())
|
||||
{
|
||||
auto const txs = flatFetchTransactions(*ledger, app);
|
||||
transactions_.reserve(txs.size());
|
||||
insertAll(txs);
|
||||
}
|
||||
insertAll(flatFetchTransactions(*ledger, app));
|
||||
else
|
||||
{
|
||||
transactions_.reserve(256);
|
||||
insertAll(ledger->txs);
|
||||
}
|
||||
}
|
||||
|
||||
std::sort(
|
||||
transactions_.begin(),
|
||||
transactions_.end(),
|
||||
[](auto const& a, auto const& b) {
|
||||
return a->getTxnSeq() < b->getTxnSeq();
|
||||
});
|
||||
void
|
||||
AcceptedLedger::insert(AcceptedLedgerTx::ref at)
|
||||
{
|
||||
assert(mMap.find(at->getIndex()) == mMap.end());
|
||||
mMap.insert(std::make_pair(at->getIndex(), at));
|
||||
}
|
||||
|
||||
} // namespace ripple
|
||||
|
||||
@@ -41,40 +41,43 @@ namespace ripple {
|
||||
the result of the a consensus process (though haven't validated
|
||||
it yet).
|
||||
*/
|
||||
class AcceptedLedger : public CountedObject<AcceptedLedger>
|
||||
class AcceptedLedger
|
||||
{
|
||||
public:
|
||||
AcceptedLedger(
|
||||
std::shared_ptr<ReadView const> const& ledger,
|
||||
Application& app);
|
||||
using pointer = std::shared_ptr<AcceptedLedger>;
|
||||
using ret = const pointer&;
|
||||
using map_t = std::map<int, AcceptedLedgerTx::pointer>;
|
||||
// mapt_t must be an ordered map!
|
||||
using value_type = map_t::value_type;
|
||||
using const_iterator = map_t::const_iterator;
|
||||
|
||||
public:
|
||||
std::shared_ptr<ReadView const> const&
|
||||
getLedger() const
|
||||
{
|
||||
return mLedger;
|
||||
}
|
||||
|
||||
std::size_t
|
||||
size() const
|
||||
const map_t&
|
||||
getMap() const
|
||||
{
|
||||
return transactions_.size();
|
||||
return mMap;
|
||||
}
|
||||
|
||||
auto
|
||||
begin() const
|
||||
int
|
||||
getTxnCount() const
|
||||
{
|
||||
return transactions_.begin();
|
||||
return mMap.size();
|
||||
}
|
||||
|
||||
auto
|
||||
end() const
|
||||
{
|
||||
return transactions_.end();
|
||||
}
|
||||
AcceptedLedger(
|
||||
std::shared_ptr<ReadView const> const& ledger,
|
||||
Application& app);
|
||||
|
||||
private:
|
||||
void insert(AcceptedLedgerTx::ref);
|
||||
|
||||
std::shared_ptr<ReadView const> mLedger;
|
||||
std::vector<std::unique_ptr<AcceptedLedgerTx>> transactions_;
|
||||
map_t mMap;
|
||||
};
|
||||
|
||||
} // namespace ripple
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
//==============================================================================
|
||||
|
||||
#include <ripple/app/ledger/AcceptedLedgerTx.h>
|
||||
#include <ripple/app/main/Application.h>
|
||||
#include <ripple/basics/Log.h>
|
||||
#include <ripple/basics/StringUtilities.h>
|
||||
#include <ripple/protocol/UintTypes.h>
|
||||
@@ -29,30 +30,72 @@ AcceptedLedgerTx::AcceptedLedgerTx(
|
||||
std::shared_ptr<ReadView const> const& ledger,
|
||||
std::shared_ptr<STTx const> const& txn,
|
||||
std::shared_ptr<STObject const> const& met,
|
||||
AccountIDCache const& accountCache)
|
||||
: mTxn(txn)
|
||||
, mMeta(txn->getTransactionID(), ledger->seq(), *met)
|
||||
, mAffected(mMeta.getAffectedAccounts())
|
||||
AccountIDCache const& accountCache,
|
||||
Logs& logs)
|
||||
: mLedger(ledger)
|
||||
, mTxn(txn)
|
||||
, mMeta(std::make_shared<TxMeta>(
|
||||
txn->getTransactionID(),
|
||||
ledger->seq(),
|
||||
*met))
|
||||
, mAffected(mMeta->getAffectedAccounts(logs.journal("View")))
|
||||
, accountCache_(accountCache)
|
||||
, logs_(logs)
|
||||
{
|
||||
assert(!ledger->open());
|
||||
|
||||
mResult = mMeta->getResultTER();
|
||||
|
||||
Serializer s;
|
||||
met->add(s);
|
||||
mRawMeta = std::move(s.modData());
|
||||
|
||||
buildJson();
|
||||
}
|
||||
|
||||
AcceptedLedgerTx::AcceptedLedgerTx(
|
||||
std::shared_ptr<ReadView const> const& ledger,
|
||||
std::shared_ptr<STTx const> const& txn,
|
||||
TER result,
|
||||
AccountIDCache const& accountCache,
|
||||
Logs& logs)
|
||||
: mLedger(ledger)
|
||||
, mTxn(txn)
|
||||
, mResult(result)
|
||||
, mAffected(txn->getMentionedAccounts())
|
||||
, accountCache_(accountCache)
|
||||
, logs_(logs)
|
||||
{
|
||||
assert(ledger->open());
|
||||
buildJson();
|
||||
}
|
||||
|
||||
std::string
|
||||
AcceptedLedgerTx::getEscMeta() const
|
||||
{
|
||||
assert(!mRawMeta.empty());
|
||||
return sqlBlobLiteral(mRawMeta);
|
||||
}
|
||||
|
||||
void
|
||||
AcceptedLedgerTx::buildJson()
|
||||
{
|
||||
mJson = Json::objectValue;
|
||||
mJson[jss::transaction] = mTxn->getJson(JsonOptions::none);
|
||||
|
||||
mJson[jss::meta] = mMeta.getJson(JsonOptions::none);
|
||||
mJson[jss::raw_meta] = strHex(mRawMeta);
|
||||
if (mMeta)
|
||||
{
|
||||
mJson[jss::meta] = mMeta->getJson(JsonOptions::none);
|
||||
mJson[jss::raw_meta] = strHex(mRawMeta);
|
||||
}
|
||||
|
||||
mJson[jss::result] = transHuman(mMeta.getResultTER());
|
||||
mJson[jss::result] = transHuman(mResult);
|
||||
|
||||
if (!mAffected.empty())
|
||||
{
|
||||
Json::Value& affected = (mJson[jss::affected] = Json::arrayValue);
|
||||
for (auto const& account : mAffected)
|
||||
affected.append(accountCache.toBase58(account));
|
||||
affected.append(accountCache_.toBase58(account));
|
||||
}
|
||||
|
||||
if (mTxn->getTxnType() == ttOFFER_CREATE)
|
||||
@@ -64,21 +107,14 @@ AcceptedLedgerTx::AcceptedLedgerTx(
|
||||
if (account != amount.issue().account)
|
||||
{
|
||||
auto const ownerFunds = accountFunds(
|
||||
*ledger,
|
||||
*mLedger,
|
||||
account,
|
||||
amount,
|
||||
fhIGNORE_FREEZE,
|
||||
beast::Journal{beast::Journal::getNullSink()});
|
||||
logs_.journal("View"));
|
||||
mJson[jss::transaction][jss::owner_funds] = ownerFunds.getText();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string
|
||||
AcceptedLedgerTx::getEscMeta() const
|
||||
{
|
||||
assert(!mRawMeta.empty());
|
||||
return sqlBlobLiteral(mRawMeta);
|
||||
}
|
||||
|
||||
} // namespace ripple
|
||||
|
||||
@@ -39,22 +39,40 @@ class Logs;
|
||||
- Which accounts are affected
|
||||
* This is used by InfoSub to report to clients
|
||||
- Cached stuff
|
||||
|
||||
@code
|
||||
@endcode
|
||||
|
||||
@see {uri}
|
||||
|
||||
@ingroup ripple_ledger
|
||||
*/
|
||||
class AcceptedLedgerTx : public CountedObject<AcceptedLedgerTx>
|
||||
class AcceptedLedgerTx
|
||||
{
|
||||
public:
|
||||
using pointer = std::shared_ptr<AcceptedLedgerTx>;
|
||||
using ref = const pointer&;
|
||||
|
||||
public:
|
||||
AcceptedLedgerTx(
|
||||
std::shared_ptr<ReadView const> const& ledger,
|
||||
std::shared_ptr<STTx const> const&,
|
||||
std::shared_ptr<STObject const> const&,
|
||||
AccountIDCache const&);
|
||||
AccountIDCache const&,
|
||||
Logs&);
|
||||
AcceptedLedgerTx(
|
||||
std::shared_ptr<ReadView const> const&,
|
||||
std::shared_ptr<STTx const> const&,
|
||||
TER,
|
||||
AccountIDCache const&,
|
||||
Logs&);
|
||||
|
||||
std::shared_ptr<STTx const> const&
|
||||
getTxn() const
|
||||
{
|
||||
return mTxn;
|
||||
}
|
||||
TxMeta const&
|
||||
std::shared_ptr<TxMeta> const&
|
||||
getMeta() const
|
||||
{
|
||||
return mMeta;
|
||||
@@ -79,28 +97,45 @@ public:
|
||||
TER
|
||||
getResult() const
|
||||
{
|
||||
return mMeta.getResultTER();
|
||||
return mResult;
|
||||
}
|
||||
std::uint32_t
|
||||
getTxnSeq() const
|
||||
{
|
||||
return mMeta.getIndex();
|
||||
return mMeta->getIndex();
|
||||
}
|
||||
|
||||
bool
|
||||
isApplied() const
|
||||
{
|
||||
return bool(mMeta);
|
||||
}
|
||||
int
|
||||
getIndex() const
|
||||
{
|
||||
return mMeta ? mMeta->getIndex() : 0;
|
||||
}
|
||||
std::string
|
||||
getEscMeta() const;
|
||||
|
||||
Json::Value const&
|
||||
Json::Value
|
||||
getJson() const
|
||||
{
|
||||
return mJson;
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<ReadView const> mLedger;
|
||||
std::shared_ptr<STTx const> mTxn;
|
||||
TxMeta mMeta;
|
||||
std::shared_ptr<TxMeta> mMeta;
|
||||
TER mResult;
|
||||
boost::container::flat_set<AccountID> mAffected;
|
||||
Blob mRawMeta;
|
||||
Json::Value mJson;
|
||||
AccountIDCache const& accountCache_;
|
||||
Logs& logs_;
|
||||
|
||||
void
|
||||
buildJson();
|
||||
};
|
||||
|
||||
} // namespace ripple
|
||||
|
||||
@@ -39,6 +39,9 @@ class InboundLedger final : public TimeoutCounter,
|
||||
public:
|
||||
using clock_type = beast::abstract_clock<std::chrono::steady_clock>;
|
||||
|
||||
using PeerDataPairType =
|
||||
std::pair<std::weak_ptr<Peer>, std::shared_ptr<protocol::TMLedgerData>>;
|
||||
|
||||
// These are the reasons we might acquire a ledger
|
||||
enum class Reason {
|
||||
HISTORY, // Acquiring past ledger
|
||||
@@ -190,9 +193,7 @@ private:
|
||||
|
||||
// Data we have received from peers
|
||||
std::mutex mReceivedDataLock;
|
||||
std::vector<
|
||||
std::pair<std::weak_ptr<Peer>, std::shared_ptr<protocol::TMLedgerData>>>
|
||||
mReceivedData;
|
||||
std::vector<PeerDataPairType> mReceivedData;
|
||||
bool mReceiveDispatched;
|
||||
std::unique_ptr<PeerSet> mPeerSet;
|
||||
};
|
||||
|
||||
@@ -29,8 +29,8 @@
|
||||
#include <ripple/app/misc/HashRouter.h>
|
||||
#include <ripple/app/misc/LoadFeeTrack.h>
|
||||
#include <ripple/app/misc/NetworkOPs.h>
|
||||
#include <ripple/app/rdb/backend/PostgresDatabase.h>
|
||||
#include <ripple/app/rdb/backend/SQLiteDatabase.h>
|
||||
#include <ripple/app/rdb/backend/RelationalDBInterfacePostgres.h>
|
||||
#include <ripple/app/rdb/backend/RelationalDBInterfaceSqlite.h>
|
||||
#include <ripple/basics/Log.h>
|
||||
#include <ripple/basics/StringUtilities.h>
|
||||
#include <ripple/basics/contract.h>
|
||||
@@ -626,7 +626,7 @@ Ledger::setup(Config const& config)
|
||||
|
||||
try
|
||||
{
|
||||
rules_ = makeRulesGivenLedger(*this, config.features);
|
||||
rules_ = Rules(*this, config.features);
|
||||
}
|
||||
catch (SHAMapMissingNode const&)
|
||||
{
|
||||
@@ -930,11 +930,9 @@ saveValidatedLedger(
|
||||
return true;
|
||||
}
|
||||
|
||||
auto const db = dynamic_cast<SQLiteDatabase*>(&app.getRelationalDatabase());
|
||||
if (!db)
|
||||
Throw<std::runtime_error>("Failed to get relational database");
|
||||
|
||||
auto const res = db->saveValidatedLedger(ledger, current);
|
||||
auto res = dynamic_cast<RelationalDBInterfaceSqlite*>(
|
||||
&app.getRelationalDBInterface())
|
||||
->saveValidatedLedger(ledger, current);
|
||||
|
||||
// Clients can now trust the database for
|
||||
// information about this ledger sequence.
|
||||
@@ -1055,7 +1053,7 @@ std::tuple<std::shared_ptr<Ledger>, std::uint32_t, uint256>
|
||||
getLatestLedger(Application& app)
|
||||
{
|
||||
const std::optional<LedgerInfo> info =
|
||||
app.getRelationalDatabase().getNewestLedgerInfo();
|
||||
app.getRelationalDBInterface().getNewestLedgerInfo();
|
||||
if (!info)
|
||||
return {std::shared_ptr<Ledger>(), {}, {}};
|
||||
return {loadLedgerHelper(*info, app, true), info->seq, info->hash};
|
||||
@@ -1065,7 +1063,7 @@ std::shared_ptr<Ledger>
|
||||
loadByIndex(std::uint32_t ledgerIndex, Application& app, bool acquire)
|
||||
{
|
||||
if (std::optional<LedgerInfo> info =
|
||||
app.getRelationalDatabase().getLedgerInfoByIndex(ledgerIndex))
|
||||
app.getRelationalDBInterface().getLedgerInfoByIndex(ledgerIndex))
|
||||
{
|
||||
std::shared_ptr<Ledger> ledger = loadLedgerHelper(*info, app, acquire);
|
||||
finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger"));
|
||||
@@ -1078,7 +1076,7 @@ std::shared_ptr<Ledger>
|
||||
loadByHash(uint256 const& ledgerHash, Application& app, bool acquire)
|
||||
{
|
||||
if (std::optional<LedgerInfo> info =
|
||||
app.getRelationalDatabase().getLedgerInfoByHash(ledgerHash))
|
||||
app.getRelationalDBInterface().getLedgerInfoByHash(ledgerHash))
|
||||
{
|
||||
std::shared_ptr<Ledger> ledger = loadLedgerHelper(*info, app, acquire);
|
||||
finishLoadByIndexOrHash(ledger, app.config(), app.journal("Ledger"));
|
||||
@@ -1167,12 +1165,9 @@ flatFetchTransactions(ReadView const& ledger, Application& app)
|
||||
return {};
|
||||
}
|
||||
|
||||
auto const db =
|
||||
dynamic_cast<PostgresDatabase*>(&app.getRelationalDatabase());
|
||||
if (!db)
|
||||
Throw<std::runtime_error>("Failed to get relational database");
|
||||
|
||||
auto nodestoreHashes = db->getTxHashes(ledger.info().seq);
|
||||
auto nodestoreHashes = dynamic_cast<RelationalDBInterfacePostgres*>(
|
||||
&app.getRelationalDBInterface())
|
||||
->getTxHashes(ledger.info().seq);
|
||||
|
||||
return flatFetchTransactions(app, nodestoreHashes);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,14 @@
|
||||
|
||||
namespace ripple {
|
||||
|
||||
// VFALCO TODO replace macros
|
||||
|
||||
#ifndef CACHED_LEDGER_NUM
|
||||
#define CACHED_LEDGER_NUM 96
|
||||
#endif
|
||||
|
||||
std::chrono::seconds constexpr CachedLedgerAge = std::chrono::minutes{2};
|
||||
|
||||
// FIXME: Need to clean up ledgers by index at some point
|
||||
|
||||
LedgerHistory::LedgerHistory(
|
||||
@@ -36,8 +44,8 @@ LedgerHistory::LedgerHistory(
|
||||
, mismatch_counter_(collector->make_counter("ledger.history", "mismatch"))
|
||||
, m_ledgers_by_hash(
|
||||
"LedgerCache",
|
||||
app_.config().getValueFor(SizedItem::ledgerSize),
|
||||
std::chrono::seconds{app_.config().getValueFor(SizedItem::ledgerAge)},
|
||||
CACHED_LEDGER_NUM,
|
||||
CachedLedgerAge,
|
||||
stopwatch(),
|
||||
app_.journal("TaggedCache"))
|
||||
, m_consensus_validated(
|
||||
@@ -515,6 +523,13 @@ LedgerHistory::fixIndex(LedgerIndex ledgerIndex, LedgerHash const& ledgerHash)
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
LedgerHistory::tune(int size, std::chrono::seconds age)
|
||||
{
|
||||
m_ledgers_by_hash.setTargetSize(size);
|
||||
m_ledgers_by_hash.setTargetAge(age);
|
||||
}
|
||||
|
||||
void
|
||||
LedgerHistory::clearLedgerCachePrior(LedgerIndex seq)
|
||||
{
|
||||
|
||||
@@ -70,6 +70,13 @@ public:
|
||||
LedgerHash
|
||||
getLedgerHash(LedgerIndex ledgerIndex);
|
||||
|
||||
/** Set the history cache's parameters
|
||||
@param size The target size of the cache
|
||||
@param age The target age of the cache, in seconds
|
||||
*/
|
||||
void
|
||||
tune(int size, std::chrono::seconds age);
|
||||
|
||||
/** Remove stale cache entries
|
||||
*/
|
||||
void
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
#ifndef RIPPLE_APP_LEDGER_LEDGERHOLDER_H_INCLUDED
|
||||
#define RIPPLE_APP_LEDGER_LEDGERHOLDER_H_INCLUDED
|
||||
|
||||
#include <ripple/basics/CountedObject.h>
|
||||
#include <ripple/basics/contract.h>
|
||||
#include <mutex>
|
||||
|
||||
@@ -36,7 +35,7 @@ namespace ripple {
|
||||
way the object always holds a value. We can use the
|
||||
genesis ledger in all cases.
|
||||
*/
|
||||
class LedgerHolder : public CountedObject<LedgerHolder>
|
||||
class LedgerHolder
|
||||
{
|
||||
public:
|
||||
// Update the held ledger
|
||||
|
||||
@@ -219,6 +219,8 @@ public:
|
||||
bool
|
||||
getFullValidatedRange(std::uint32_t& minVal, std::uint32_t& maxVal);
|
||||
|
||||
void
|
||||
tune(int size, std::chrono::seconds age);
|
||||
void
|
||||
sweep();
|
||||
float
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
#ifndef RIPPLE_APP_LEDGER_LEDGERREPLAY_H_INCLUDED
|
||||
#define RIPPLE_APP_LEDGER_LEDGERREPLAY_H_INCLUDED
|
||||
|
||||
#include <ripple/basics/CountedObject.h>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -30,7 +29,7 @@ namespace ripple {
|
||||
class Ledger;
|
||||
class STTx;
|
||||
|
||||
class LedgerReplay : public CountedObject<LedgerReplay>
|
||||
class LedgerReplay
|
||||
{
|
||||
std::shared_ptr<Ledger const> parent_;
|
||||
std::shared_ptr<Ledger const> replay_;
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
#include <ripple/app/ledger/LedgerMaster.h>
|
||||
#include <ripple/app/ledger/OrderBookDB.h>
|
||||
#include <ripple/app/main/Application.h>
|
||||
#include <ripple/app/misc/NetworkOPs.h>
|
||||
#include <ripple/basics/Log.h>
|
||||
#include <ripple/core/Config.h>
|
||||
#include <ripple/core/JobQueue.h>
|
||||
@@ -29,72 +28,70 @@
|
||||
namespace ripple {
|
||||
|
||||
OrderBookDB::OrderBookDB(Application& app)
|
||||
: app_(app), seq_(0), j_(app.journal("OrderBookDB"))
|
||||
: app_(app), mSeq(0), j_(app.journal("OrderBookDB"))
|
||||
{
|
||||
}
|
||||
|
||||
void
|
||||
OrderBookDB::invalidate()
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
mSeq = 0;
|
||||
}
|
||||
|
||||
void
|
||||
OrderBookDB::setup(std::shared_ptr<ReadView const> const& ledger)
|
||||
{
|
||||
if (!app_.config().standalone() && app_.getOPs().isNeedNetworkLedger())
|
||||
{
|
||||
JLOG(j_.warn()) << "Eliding full order book update: no ledger";
|
||||
return;
|
||||
std::lock_guard sl(mLock);
|
||||
auto seq = ledger->info().seq;
|
||||
|
||||
// Do a full update every 256 ledgers
|
||||
if (mSeq != 0)
|
||||
{
|
||||
if (seq == mSeq)
|
||||
return;
|
||||
if ((seq > mSeq) && ((seq - mSeq) < 256))
|
||||
return;
|
||||
if ((seq < mSeq) && ((mSeq - seq) < 16))
|
||||
return;
|
||||
}
|
||||
|
||||
JLOG(j_.debug()) << "Advancing from " << mSeq << " to " << seq;
|
||||
|
||||
mSeq = seq;
|
||||
}
|
||||
|
||||
auto seq = seq_.load();
|
||||
|
||||
if (seq != 0)
|
||||
{
|
||||
if ((seq > ledger->seq()) && ((ledger->seq() - seq) < 25600))
|
||||
return;
|
||||
|
||||
if ((ledger->seq() <= seq) && ((seq - ledger->seq()) < 16))
|
||||
return;
|
||||
}
|
||||
|
||||
if (seq_.exchange(ledger->seq()) != seq)
|
||||
return;
|
||||
|
||||
JLOG(j_.debug()) << "Full order book update: " << seq << " to "
|
||||
<< ledger->seq();
|
||||
|
||||
if (app_.config().PATH_SEARCH_MAX != 0)
|
||||
{
|
||||
if (app_.config().standalone())
|
||||
update(ledger);
|
||||
else
|
||||
app_.getJobQueue().addJob(
|
||||
jtUPDATE_PF,
|
||||
"OrderBookDB::update: " + std::to_string(ledger->seq()),
|
||||
[this, ledger]() { update(ledger); });
|
||||
jtUPDATE_PF, "OrderBookDB::update", [this, ledger]() {
|
||||
update(ledger);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void
|
||||
OrderBookDB::update(std::shared_ptr<ReadView const> const& ledger)
|
||||
{
|
||||
if (app_.config().PATH_SEARCH_MAX == 0)
|
||||
return; // pathfinding has been disabled
|
||||
hash_set<uint256> seen;
|
||||
OrderBookDB::IssueToOrderBook destMap;
|
||||
OrderBookDB::IssueToOrderBook sourceMap;
|
||||
hash_set<Issue> XRPBooks;
|
||||
|
||||
// A newer full update job is pending
|
||||
if (auto const seq = seq_.load(); seq > ledger->seq())
|
||||
JLOG(j_.debug()) << "OrderBookDB::update>";
|
||||
|
||||
if (app_.config().PATH_SEARCH_MAX == 0)
|
||||
{
|
||||
JLOG(j_.debug()) << "Eliding update for " << ledger->seq()
|
||||
<< " because of pending update to later " << seq;
|
||||
// pathfinding has been disabled
|
||||
return;
|
||||
}
|
||||
|
||||
decltype(allBooks_) allBooks;
|
||||
decltype(xrpBooks_) xrpBooks;
|
||||
|
||||
allBooks.reserve(allBooks_.size());
|
||||
xrpBooks.reserve(xrpBooks_.size());
|
||||
|
||||
JLOG(j_.debug()) << "Beginning update (" << ledger->seq() << ")";
|
||||
|
||||
// walk through the entire ledger looking for orderbook entries
|
||||
int cnt = 0;
|
||||
int books = 0;
|
||||
|
||||
try
|
||||
{
|
||||
@@ -103,8 +100,9 @@ OrderBookDB::update(std::shared_ptr<ReadView const> const& ledger)
|
||||
if (app_.isStopping())
|
||||
{
|
||||
JLOG(j_.info())
|
||||
<< "Update halted because the process is stopping";
|
||||
seq_.store(0);
|
||||
<< "OrderBookDB::update exiting due to isStopping";
|
||||
std::lock_guard sl(mLock);
|
||||
mSeq = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -113,38 +111,40 @@ OrderBookDB::update(std::shared_ptr<ReadView const> const& ledger)
|
||||
sle->getFieldH256(sfRootIndex) == sle->key())
|
||||
{
|
||||
Book book;
|
||||
|
||||
book.in.currency = sle->getFieldH160(sfTakerPaysCurrency);
|
||||
book.in.account = sle->getFieldH160(sfTakerPaysIssuer);
|
||||
book.out.currency = sle->getFieldH160(sfTakerGetsCurrency);
|
||||
book.out.account = sle->getFieldH160(sfTakerGetsIssuer);
|
||||
book.out.currency = sle->getFieldH160(sfTakerGetsCurrency);
|
||||
|
||||
allBooks[book.in].insert(book.out);
|
||||
|
||||
if (isXRP(book.out))
|
||||
xrpBooks.insert(book.in);
|
||||
|
||||
++cnt;
|
||||
uint256 index = getBookBase(book);
|
||||
if (seen.insert(index).second)
|
||||
{
|
||||
auto orderBook = std::make_shared<OrderBook>(index, book);
|
||||
sourceMap[book.in].push_back(orderBook);
|
||||
destMap[book.out].push_back(orderBook);
|
||||
if (isXRP(book.out))
|
||||
XRPBooks.insert(book.in);
|
||||
++books;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SHAMapMissingNode const& mn)
|
||||
{
|
||||
JLOG(j_.info()) << "Missing node in " << ledger->seq()
|
||||
<< " during update: " << mn.what();
|
||||
seq_.store(0);
|
||||
JLOG(j_.info()) << "OrderBookDB::update: " << mn.what();
|
||||
std::lock_guard sl(mLock);
|
||||
mSeq = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
JLOG(j_.debug()) << "Update completed (" << ledger->seq() << "): " << cnt
|
||||
<< " books found";
|
||||
|
||||
JLOG(j_.debug()) << "OrderBookDB::update< " << books << " books found";
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
allBooks_.swap(allBooks);
|
||||
xrpBooks_.swap(xrpBooks);
|
||||
}
|
||||
|
||||
mXRPBooks.swap(XRPBooks);
|
||||
mSourceMap.swap(sourceMap);
|
||||
mDestMap.swap(destMap);
|
||||
}
|
||||
app_.getLedgerMaster().newOrderBookDB();
|
||||
}
|
||||
|
||||
@@ -152,50 +152,60 @@ void
|
||||
OrderBookDB::addOrderBook(Book const& book)
|
||||
{
|
||||
bool toXRP = isXRP(book.out);
|
||||
|
||||
std::lock_guard sl(mLock);
|
||||
|
||||
allBooks_[book.in].insert(book.out);
|
||||
|
||||
if (toXRP)
|
||||
xrpBooks_.insert(book.in);
|
||||
{
|
||||
// We don't want to search through all the to-XRP or from-XRP order
|
||||
// books!
|
||||
for (auto ob : mSourceMap[book.in])
|
||||
{
|
||||
if (isXRP(ob->getCurrencyOut())) // also to XRP
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (auto ob : mDestMap[book.out])
|
||||
{
|
||||
if (ob->getCurrencyIn() == book.in.currency &&
|
||||
ob->getIssuerIn() == book.in.account)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
uint256 index = getBookBase(book);
|
||||
auto orderBook = std::make_shared<OrderBook>(index, book);
|
||||
|
||||
mSourceMap[book.in].push_back(orderBook);
|
||||
mDestMap[book.out].push_back(orderBook);
|
||||
if (toXRP)
|
||||
mXRPBooks.insert(book.in);
|
||||
}
|
||||
|
||||
// return list of all orderbooks that want this issuerID and currencyID
|
||||
std::vector<Book>
|
||||
OrderBook::List
|
||||
OrderBookDB::getBooksByTakerPays(Issue const& issue)
|
||||
{
|
||||
std::vector<Book> ret;
|
||||
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
|
||||
if (auto it = allBooks_.find(issue); it != allBooks_.end())
|
||||
{
|
||||
ret.reserve(it->second.size());
|
||||
|
||||
for (auto const& gets : it->second)
|
||||
ret.push_back(Book(issue, gets));
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
std::lock_guard sl(mLock);
|
||||
auto it = mSourceMap.find(issue);
|
||||
return it == mSourceMap.end() ? OrderBook::List() : it->second;
|
||||
}
|
||||
|
||||
int
|
||||
OrderBookDB::getBookSize(Issue const& issue)
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
if (auto it = allBooks_.find(issue); it != allBooks_.end())
|
||||
return static_cast<int>(it->second.size());
|
||||
return 0;
|
||||
auto it = mSourceMap.find(issue);
|
||||
return it == mSourceMap.end() ? 0 : it->second.size();
|
||||
}
|
||||
|
||||
bool
|
||||
OrderBookDB::isBookToXRP(Issue const& issue)
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
return xrpBooks_.count(issue) > 0;
|
||||
return mXRPBooks.count(issue) > 0;
|
||||
}
|
||||
|
||||
BookListeners::pointer
|
||||
@@ -237,48 +247,62 @@ OrderBookDB::processTxn(
|
||||
Json::Value const& jvObj)
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
|
||||
// For this particular transaction, maintain the set of unique
|
||||
// subscriptions that have already published it. This prevents sending
|
||||
// the transaction multiple times if it touches multiple ltOFFER
|
||||
// entries for the same book, or if it touches multiple books and a
|
||||
// single client has subscribed to those books.
|
||||
hash_set<std::uint64_t> havePublished;
|
||||
|
||||
for (auto const& node : alTx.getMeta().getNodes())
|
||||
if (alTx.getResult() == tesSUCCESS)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (node.getFieldU16(sfLedgerEntryType) == ltOFFER)
|
||||
{
|
||||
auto process = [&, this](SField const& field) {
|
||||
if (auto data = dynamic_cast<STObject const*>(
|
||||
node.peekAtPField(field));
|
||||
data && data->isFieldPresent(sfTakerPays) &&
|
||||
data->isFieldPresent(sfTakerGets))
|
||||
{
|
||||
auto listeners = getBookListeners(
|
||||
{data->getFieldAmount(sfTakerGets).issue(),
|
||||
data->getFieldAmount(sfTakerPays).issue()});
|
||||
if (listeners)
|
||||
listeners->publish(jvObj, havePublished);
|
||||
}
|
||||
};
|
||||
// For this particular transaction, maintain the set of unique
|
||||
// subscriptions that have already published it. This prevents sending
|
||||
// the transaction multiple times if it touches multiple ltOFFER
|
||||
// entries for the same book, or if it touches multiple books and a
|
||||
// single client has subscribed to those books.
|
||||
hash_set<std::uint64_t> havePublished;
|
||||
|
||||
// We need a field that contains the TakerGets and TakerPays
|
||||
// parameters.
|
||||
if (node.getFName() == sfModifiedNode)
|
||||
process(sfPreviousFields);
|
||||
else if (node.getFName() == sfCreatedNode)
|
||||
process(sfNewFields);
|
||||
else if (node.getFName() == sfDeletedNode)
|
||||
process(sfFinalFields);
|
||||
}
|
||||
}
|
||||
catch (std::exception const& ex)
|
||||
// Check if this is an offer or an offer cancel or a payment that
|
||||
// consumes an offer.
|
||||
// Check to see what the meta looks like.
|
||||
for (auto& node : alTx.getMeta()->getNodes())
|
||||
{
|
||||
JLOG(j_.info())
|
||||
<< "processTxn: field not found (" << ex.what() << ")";
|
||||
try
|
||||
{
|
||||
if (node.getFieldU16(sfLedgerEntryType) == ltOFFER)
|
||||
{
|
||||
SField const* field = nullptr;
|
||||
|
||||
// We need a field that contains the TakerGets and TakerPays
|
||||
// parameters.
|
||||
if (node.getFName() == sfModifiedNode)
|
||||
field = &sfPreviousFields;
|
||||
else if (node.getFName() == sfCreatedNode)
|
||||
field = &sfNewFields;
|
||||
else if (node.getFName() == sfDeletedNode)
|
||||
field = &sfFinalFields;
|
||||
|
||||
if (field)
|
||||
{
|
||||
auto data = dynamic_cast<const STObject*>(
|
||||
node.peekAtPField(*field));
|
||||
|
||||
if (data && data->isFieldPresent(sfTakerPays) &&
|
||||
data->isFieldPresent(sfTakerGets))
|
||||
{
|
||||
// determine the OrderBook
|
||||
Book b{
|
||||
data->getFieldAmount(sfTakerGets).issue(),
|
||||
data->getFieldAmount(sfTakerPays).issue()};
|
||||
|
||||
auto listeners = getBookListeners(b);
|
||||
if (listeners)
|
||||
{
|
||||
listeners->publish(jvObj, havePublished);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (std::exception const&)
|
||||
{
|
||||
JLOG(j_.info())
|
||||
<< "Fields not found in OrderBookDB::processTxn";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include <ripple/app/ledger/AcceptedLedgerTx.h>
|
||||
#include <ripple/app/ledger/BookListeners.h>
|
||||
#include <ripple/app/main/Application.h>
|
||||
#include <ripple/app/misc/OrderBook.h>
|
||||
#include <mutex>
|
||||
|
||||
namespace ripple {
|
||||
@@ -36,13 +37,15 @@ public:
|
||||
setup(std::shared_ptr<ReadView const> const& ledger);
|
||||
void
|
||||
update(std::shared_ptr<ReadView const> const& ledger);
|
||||
void
|
||||
invalidate();
|
||||
|
||||
void
|
||||
addOrderBook(Book const&);
|
||||
|
||||
/** @return a list of all orderbooks that want this issuerID and currencyID.
|
||||
*/
|
||||
std::vector<Book>
|
||||
OrderBook::List
|
||||
getBooksByTakerPays(Issue const&);
|
||||
|
||||
/** @return a count of all orderbooks that want this issuerID and
|
||||
@@ -65,14 +68,22 @@ public:
|
||||
const AcceptedLedgerTx& alTx,
|
||||
Json::Value const& jvObj);
|
||||
|
||||
using IssueToOrderBook = hash_map<Issue, OrderBook::List>;
|
||||
|
||||
private:
|
||||
void
|
||||
rawAddBook(Book const&);
|
||||
|
||||
Application& app_;
|
||||
|
||||
// Maps order books by "issue in" to "issue out":
|
||||
hardened_hash_map<Issue, hardened_hash_set<Issue>> allBooks_;
|
||||
// by ci/ii
|
||||
IssueToOrderBook mSourceMap;
|
||||
|
||||
// by co/io
|
||||
IssueToOrderBook mDestMap;
|
||||
|
||||
// does an order book to XRP exist
|
||||
hash_set<Issue> xrpBooks_;
|
||||
hash_set<Issue> mXRPBooks;
|
||||
|
||||
std::recursive_mutex mLock;
|
||||
|
||||
@@ -80,7 +91,7 @@ private:
|
||||
|
||||
BookToListenersMap mListeners;
|
||||
|
||||
std::atomic<std::uint32_t> seq_;
|
||||
std::uint32_t mSeq;
|
||||
|
||||
beast::Journal const j_;
|
||||
};
|
||||
|
||||
@@ -162,7 +162,7 @@ There are also indirect peer queries. If there have been timeouts while
|
||||
acquiring ledger data then a server may issue indirect queries. In that
|
||||
case the server receiving the indirect query passes the query along to any
|
||||
of its peers that may have the requested data. This is important if the
|
||||
network has a byzantine failure. It also helps protect the validation
|
||||
network has a byzantine failure. If also helps protect the validation
|
||||
network. A validator may need to get a peer set from one of the other
|
||||
validators, and indirect queries improve the likelihood of success with
|
||||
that.
|
||||
@@ -487,3 +487,4 @@ ledger(s) for missing nodes in the back end node store
|
||||
---
|
||||
|
||||
# References #
|
||||
|
||||
|
||||
@@ -33,10 +33,7 @@
|
||||
#include <ripple/resource/Fees.h>
|
||||
#include <ripple/shamap/SHAMapNodeID.h>
|
||||
|
||||
#include <boost/iterator/function_output_iterator.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <random>
|
||||
|
||||
namespace ripple {
|
||||
|
||||
@@ -44,19 +41,19 @@ using namespace std::chrono_literals;
|
||||
|
||||
enum {
|
||||
// Number of peers to start with
|
||||
peerCountStart = 5
|
||||
peerCountStart = 4
|
||||
|
||||
// Number of peers to add on a timeout
|
||||
,
|
||||
peerCountAdd = 3
|
||||
peerCountAdd = 2
|
||||
|
||||
// how many timeouts before we give up
|
||||
,
|
||||
ledgerTimeoutRetriesMax = 6
|
||||
ledgerTimeoutRetriesMax = 10
|
||||
|
||||
// how many timeouts before we get aggressive
|
||||
,
|
||||
ledgerBecomeAggressiveThreshold = 4
|
||||
ledgerBecomeAggressiveThreshold = 6
|
||||
|
||||
// Number of nodes to find initially
|
||||
,
|
||||
@@ -68,11 +65,11 @@ enum {
|
||||
|
||||
// Number of nodes to request blindly
|
||||
,
|
||||
reqNodes = 12
|
||||
reqNodes = 8
|
||||
};
|
||||
|
||||
// millisecond for each ledger timeout
|
||||
auto constexpr ledgerAcquireTimeout = 3000ms;
|
||||
auto constexpr ledgerAcquireTimeout = 2500ms;
|
||||
|
||||
InboundLedger::InboundLedger(
|
||||
Application& app,
|
||||
@@ -604,7 +601,7 @@ InboundLedger::trigger(std::shared_ptr<Peer> const& peer, TriggerReason reason)
|
||||
tmBH.set_ledgerhash(hash_.begin(), hash_.size());
|
||||
for (auto const& p : need)
|
||||
{
|
||||
JLOG(journal_.debug()) << "Want: " << p.second;
|
||||
JLOG(journal_.warn()) << "Want: " << p.second;
|
||||
|
||||
if (!typeSet)
|
||||
{
|
||||
@@ -955,23 +952,22 @@ InboundLedger::receiveNode(protocol::TMLedgerData& packet, SHAMapAddNode& san)
|
||||
|
||||
try
|
||||
{
|
||||
auto const f = filter.get();
|
||||
|
||||
for (auto const& node : packet.nodes())
|
||||
{
|
||||
auto const nodeID = deserializeSHAMapNodeID(node.nodeid());
|
||||
|
||||
if (!nodeID)
|
||||
throw std::runtime_error("data does not properly deserialize");
|
||||
{
|
||||
san.incInvalid();
|
||||
return;
|
||||
}
|
||||
|
||||
if (nodeID->isRoot())
|
||||
{
|
||||
san += map.addRootNode(rootHash, makeSlice(node.nodedata()), f);
|
||||
}
|
||||
san += map.addRootNode(
|
||||
rootHash, makeSlice(node.nodedata()), filter.get());
|
||||
else
|
||||
{
|
||||
san += map.addKnownNode(*nodeID, makeSlice(node.nodedata()), f);
|
||||
}
|
||||
san += map.addKnownNode(
|
||||
*nodeID, makeSlice(node.nodedata()), filter.get());
|
||||
|
||||
if (!san.isGood())
|
||||
{
|
||||
@@ -1124,19 +1120,19 @@ InboundLedger::processData(
|
||||
std::shared_ptr<Peer> peer,
|
||||
protocol::TMLedgerData& packet)
|
||||
{
|
||||
ScopedLockType sl(mtx_);
|
||||
|
||||
if (packet.type() == protocol::liBASE)
|
||||
{
|
||||
if (packet.nodes().empty())
|
||||
if (packet.nodes_size() < 1)
|
||||
{
|
||||
JLOG(journal_.warn()) << peer->id() << ": empty header data";
|
||||
JLOG(journal_.warn()) << "Got empty header data";
|
||||
peer->charge(Resource::feeInvalidRequest);
|
||||
return -1;
|
||||
}
|
||||
|
||||
SHAMapAddNode san;
|
||||
|
||||
ScopedLockType sl(mtx_);
|
||||
|
||||
try
|
||||
{
|
||||
if (!mHaveHeader)
|
||||
@@ -1181,18 +1177,13 @@ InboundLedger::processData(
|
||||
if ((packet.type() == protocol::liTX_NODE) ||
|
||||
(packet.type() == protocol::liAS_NODE))
|
||||
{
|
||||
std::string type = packet.type() == protocol::liTX_NODE ? "liTX_NODE: "
|
||||
: "liAS_NODE: ";
|
||||
|
||||
if (packet.nodes().empty())
|
||||
if (packet.nodes().size() == 0)
|
||||
{
|
||||
JLOG(journal_.info()) << peer->id() << ": response with no nodes";
|
||||
JLOG(journal_.info()) << "Got response with no nodes";
|
||||
peer->charge(Resource::feeInvalidRequest);
|
||||
return -1;
|
||||
}
|
||||
|
||||
ScopedLockType sl(mtx_);
|
||||
|
||||
// Verify node IDs and data are complete
|
||||
for (auto const& node : packet.nodes())
|
||||
{
|
||||
@@ -1207,10 +1198,14 @@ InboundLedger::processData(
|
||||
SHAMapAddNode san;
|
||||
receiveNode(packet, san);
|
||||
|
||||
JLOG(journal_.debug())
|
||||
<< "Ledger "
|
||||
<< ((packet.type() == protocol::liTX_NODE) ? "TX" : "AS")
|
||||
<< " node stats: " << san.get();
|
||||
if (packet.type() == protocol::liTX_NODE)
|
||||
{
|
||||
JLOG(journal_.debug()) << "Ledger TX node stats: " << san.get();
|
||||
}
|
||||
else
|
||||
{
|
||||
JLOG(journal_.debug()) << "Ledger AS node stats: " << san.get();
|
||||
}
|
||||
|
||||
if (san.isUseful())
|
||||
progress_ = true;
|
||||
@@ -1222,100 +1217,20 @@ InboundLedger::processData(
|
||||
return -1;
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
// Track the amount of useful data that each peer returns
|
||||
struct PeerDataCounts
|
||||
{
|
||||
// Map from peer to amount of useful the peer returned
|
||||
std::unordered_map<std::shared_ptr<Peer>, int> counts;
|
||||
// The largest amount of useful data that any peer returned
|
||||
int maxCount = 0;
|
||||
|
||||
// Update the data count for a peer
|
||||
void
|
||||
update(std::shared_ptr<Peer>&& peer, int dataCount)
|
||||
{
|
||||
if (dataCount <= 0)
|
||||
return;
|
||||
maxCount = std::max(maxCount, dataCount);
|
||||
auto i = counts.find(peer);
|
||||
if (i == counts.end())
|
||||
{
|
||||
counts.emplace(std::move(peer), dataCount);
|
||||
return;
|
||||
}
|
||||
i->second = std::max(i->second, dataCount);
|
||||
}
|
||||
|
||||
// Prune all the peers that didn't return enough data.
|
||||
void
|
||||
prune()
|
||||
{
|
||||
// Remove all the peers that didn't return at least half as much data as
|
||||
// the best peer
|
||||
auto const thresh = maxCount / 2;
|
||||
auto i = counts.begin();
|
||||
while (i != counts.end())
|
||||
{
|
||||
if (i->second < thresh)
|
||||
i = counts.erase(i);
|
||||
else
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
// call F with the `peer` parameter with a random sample of at most n values
|
||||
// of the counts vector.
|
||||
template <class F>
|
||||
void
|
||||
sampleN(std::size_t n, F&& f)
|
||||
{
|
||||
if (counts.empty())
|
||||
return;
|
||||
|
||||
auto outFunc = [&f](auto&& v) { f(v.first); };
|
||||
std::minstd_rand rng{std::random_device{}()};
|
||||
#if _MSC_VER
|
||||
std::vector<std::pair<std::shared_ptr<Peer>, int>> s;
|
||||
s.reserve(n);
|
||||
std::sample(
|
||||
counts.begin(), counts.end(), std::back_inserter(s), n, rng);
|
||||
for (auto& v : s)
|
||||
{
|
||||
outFunc(v);
|
||||
}
|
||||
#else
|
||||
std::sample(
|
||||
counts.begin(),
|
||||
counts.end(),
|
||||
boost::make_function_output_iterator(outFunc),
|
||||
n,
|
||||
rng);
|
||||
#endif
|
||||
}
|
||||
};
|
||||
} // namespace detail
|
||||
|
||||
/** Process pending TMLedgerData
|
||||
Query the a random sample of the 'best' peers
|
||||
Query the 'best' peer
|
||||
*/
|
||||
void
|
||||
InboundLedger::runData()
|
||||
{
|
||||
// Maximum number of peers to request data from
|
||||
constexpr std::size_t maxUsefulPeers = 6;
|
||||
std::shared_ptr<Peer> chosenPeer;
|
||||
int chosenPeerCount = -1;
|
||||
|
||||
decltype(mReceivedData) data;
|
||||
|
||||
// Reserve some memory so the first couple iterations don't reallocate
|
||||
data.reserve(8);
|
||||
|
||||
detail::PeerDataCounts dataCounts;
|
||||
std::vector<PeerDataPairType> data;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
data.clear();
|
||||
|
||||
{
|
||||
std::lock_guard sl(mReceivedDataLock);
|
||||
|
||||
@@ -1328,22 +1243,24 @@ InboundLedger::runData()
|
||||
data.swap(mReceivedData);
|
||||
}
|
||||
|
||||
// Select the peer that gives us the most nodes that are useful,
|
||||
// breaking ties in favor of the peer that responded first.
|
||||
for (auto& entry : data)
|
||||
{
|
||||
if (auto peer = entry.first.lock())
|
||||
{
|
||||
int count = processData(peer, *(entry.second));
|
||||
dataCounts.update(std::move(peer), count);
|
||||
if (count > chosenPeerCount)
|
||||
{
|
||||
chosenPeerCount = count;
|
||||
chosenPeer = std::move(peer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Select a random sample of the peers that gives us the most nodes that are
|
||||
// useful
|
||||
dataCounts.prune();
|
||||
dataCounts.sampleN(maxUsefulPeers, [&](std::shared_ptr<Peer> const& peer) {
|
||||
trigger(peer, TriggerReason::reply);
|
||||
});
|
||||
if (chosenPeer)
|
||||
trigger(chosenPeer, TriggerReason::reply);
|
||||
}
|
||||
|
||||
Json::Value
|
||||
|
||||
@@ -74,12 +74,6 @@ public:
|
||||
reason != InboundLedger::Reason::SHARD ||
|
||||
(seq != 0 && app_.getShardStore()));
|
||||
|
||||
// probably not the right rule
|
||||
if (app_.getOPs().isNeedNetworkLedger() &&
|
||||
(reason != InboundLedger::Reason::GENERIC) &&
|
||||
(reason != InboundLedger::Reason::CONSENSUS))
|
||||
return {};
|
||||
|
||||
bool isNew = true;
|
||||
std::shared_ptr<InboundLedger> inbound;
|
||||
{
|
||||
@@ -88,7 +82,6 @@ public:
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
auto it = mLedgers.find(hash);
|
||||
if (it != mLedgers.end())
|
||||
{
|
||||
|
||||
@@ -71,7 +71,6 @@ public:
|
||||
, m_zeroSet(m_map[uint256()])
|
||||
, m_gotSet(std::move(gotSet))
|
||||
, m_peerSetBuilder(std::move(peerSetBuilder))
|
||||
, j_(app_.journal("InboundTransactions"))
|
||||
{
|
||||
m_zeroSet.mSet = std::make_shared<SHAMap>(
|
||||
SHAMapType::TRANSACTION, uint256(), app_.getNodeFamily());
|
||||
@@ -100,7 +99,9 @@ public:
|
||||
{
|
||||
std::lock_guard sl(mLock);
|
||||
|
||||
if (auto it = m_map.find(hash); it != m_map.end())
|
||||
auto it = m_map.find(hash);
|
||||
|
||||
if (it != m_map.end())
|
||||
{
|
||||
if (acquire)
|
||||
{
|
||||
@@ -139,8 +140,11 @@ public:
|
||||
{
|
||||
protocol::TMLedgerData& packet = *packet_ptr;
|
||||
|
||||
JLOG(j_.trace()) << "Got data (" << packet.nodes().size()
|
||||
<< ") for acquiring ledger: " << hash;
|
||||
JLOG(app_.journal("InboundLedger").trace())
|
||||
<< "Got data (" << packet.nodes().size()
|
||||
<< ") "
|
||||
"for acquiring ledger: "
|
||||
<< hash;
|
||||
|
||||
TransactionAcquire::pointer ta = getAcquire(hash);
|
||||
|
||||
@@ -150,9 +154,8 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::pair<SHAMapNodeID, Slice>> data;
|
||||
data.reserve(packet.nodes().size());
|
||||
|
||||
std::list<SHAMapNodeID> nodeIDs;
|
||||
std::list<Blob> nodeData;
|
||||
for (auto const& node : packet.nodes())
|
||||
{
|
||||
if (!node.has_nodeid() || !node.has_nodedata())
|
||||
@@ -169,10 +172,12 @@ public:
|
||||
return;
|
||||
}
|
||||
|
||||
data.emplace_back(std::make_pair(*id, makeSlice(node.nodedata())));
|
||||
nodeIDs.emplace_back(*id);
|
||||
nodeData.emplace_back(
|
||||
node.nodedata().begin(), node.nodedata().end());
|
||||
}
|
||||
|
||||
if (!ta->takeNodes(data, peer).isUseful())
|
||||
if (!ta->takeNodes(nodeIDs, nodeData, peer).isUseful())
|
||||
peer->charge(Resource::feeUnwantedData);
|
||||
}
|
||||
|
||||
@@ -257,8 +262,6 @@ private:
|
||||
std::function<void(std::shared_ptr<SHAMap> const&, bool)> m_gotSet;
|
||||
|
||||
std::unique_ptr<PeerSetBuilder> m_peerSetBuilder;
|
||||
|
||||
beast::Journal j_;
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
@@ -34,7 +34,8 @@
|
||||
#include <ripple/app/misc/TxQ.h>
|
||||
#include <ripple/app/misc/ValidatorList.h>
|
||||
#include <ripple/app/paths/PathRequests.h>
|
||||
#include <ripple/app/rdb/backend/PostgresDatabase.h>
|
||||
#include <ripple/app/rdb/RelationalDBInterface_postgres.h>
|
||||
#include <ripple/app/rdb/backend/RelationalDBInterfacePostgres.h>
|
||||
#include <ripple/app/tx/apply.h>
|
||||
#include <ripple/basics/Log.h>
|
||||
#include <ripple/basics/MathUtilities.h>
|
||||
@@ -260,13 +261,8 @@ LedgerMaster::getPublishedLedgerAge()
|
||||
std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch();
|
||||
ret -= pubClose;
|
||||
ret = (ret > 0s) ? ret : 0s;
|
||||
static std::chrono::seconds lastRet = -1s;
|
||||
|
||||
if (ret != lastRet)
|
||||
{
|
||||
JLOG(m_journal.trace()) << "Published ledger age is " << ret.count();
|
||||
lastRet = ret;
|
||||
}
|
||||
JLOG(m_journal.trace()) << "Published ledger age is " << ret.count();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -277,10 +273,10 @@ LedgerMaster::getValidatedLedgerAge()
|
||||
|
||||
#ifdef RIPPLED_REPORTING
|
||||
if (app_.config().reporting())
|
||||
return static_cast<PostgresDatabase*>(&app_.getRelationalDatabase())
|
||||
return static_cast<RelationalDBInterfacePostgres*>(
|
||||
&app_.getRelationalDBInterface())
|
||||
->getValidatedLedgerAge();
|
||||
#endif
|
||||
|
||||
std::chrono::seconds valClose{mValidLedgerSign.load()};
|
||||
if (valClose == 0s)
|
||||
{
|
||||
@@ -291,13 +287,8 @@ LedgerMaster::getValidatedLedgerAge()
|
||||
std::chrono::seconds ret = app_.timeKeeper().closeTime().time_since_epoch();
|
||||
ret -= valClose;
|
||||
ret = (ret > 0s) ? ret : 0s;
|
||||
static std::chrono::seconds lastRet = -1s;
|
||||
|
||||
if (ret != lastRet)
|
||||
{
|
||||
JLOG(m_journal.trace()) << "Validated ledger age is " << ret.count();
|
||||
lastRet = ret;
|
||||
}
|
||||
JLOG(m_journal.trace()) << "Validated ledger age is " << ret.count();
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -308,7 +299,8 @@ LedgerMaster::isCaughtUp(std::string& reason)
|
||||
|
||||
#ifdef RIPPLED_REPORTING
|
||||
if (app_.config().reporting())
|
||||
return static_cast<PostgresDatabase*>(&app_.getRelationalDatabase())
|
||||
return static_cast<RelationalDBInterfacePostgres*>(
|
||||
&app_.getRelationalDBInterface())
|
||||
->isCaughtUp(reason);
|
||||
#endif
|
||||
|
||||
@@ -741,7 +733,7 @@ LedgerMaster::tryFill(std::shared_ptr<Ledger const> ledger)
|
||||
mCompleteLedgers.insert(range(minHas, maxHas));
|
||||
}
|
||||
maxHas = minHas;
|
||||
ledgerHashes = app_.getRelationalDatabase().getHashesByIndex(
|
||||
ledgerHashes = app_.getRelationalDBInterface().getHashesByIndex(
|
||||
(seq < 500) ? 0 : (seq - 499), seq);
|
||||
it = ledgerHashes.find(seq);
|
||||
|
||||
@@ -925,8 +917,8 @@ LedgerMaster::setFullLedger(
|
||||
{
|
||||
// Check the SQL database's entry for the sequence before this
|
||||
// ledger, if it's not this ledger's parent, invalidate it
|
||||
uint256 prevHash =
|
||||
app_.getRelationalDatabase().getHashByIndex(ledger->info().seq - 1);
|
||||
uint256 prevHash = app_.getRelationalDBInterface().getHashByIndex(
|
||||
ledger->info().seq - 1);
|
||||
if (prevHash.isNonZero() && prevHash != ledger->info().parentHash)
|
||||
clearLedger(ledger->info().seq - 1);
|
||||
}
|
||||
@@ -1491,14 +1483,12 @@ LedgerMaster::updatePaths()
|
||||
if (app_.getOPs().isNeedNetworkLedger())
|
||||
{
|
||||
--mPathFindThread;
|
||||
JLOG(m_journal.debug()) << "Need network ledger for updating paths";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
while (!app_.getJobQueue().isStopping())
|
||||
{
|
||||
JLOG(m_journal.debug()) << "updatePaths running";
|
||||
std::shared_ptr<ReadView const> lastLedger;
|
||||
{
|
||||
std::lock_guard ml(m_mutex);
|
||||
@@ -1516,7 +1506,6 @@ LedgerMaster::updatePaths()
|
||||
else
|
||||
{ // Nothing to do
|
||||
--mPathFindThread;
|
||||
JLOG(m_journal.debug()) << "Nothing to do for updating paths";
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1538,31 +1527,7 @@ LedgerMaster::updatePaths()
|
||||
|
||||
try
|
||||
{
|
||||
auto& pathRequests = app_.getPathRequests();
|
||||
{
|
||||
std::lock_guard ml(m_mutex);
|
||||
if (!pathRequests.requestsPending())
|
||||
{
|
||||
--mPathFindThread;
|
||||
JLOG(m_journal.debug())
|
||||
<< "No path requests found. Nothing to do for updating "
|
||||
"paths. "
|
||||
<< mPathFindThread << " jobs remaining";
|
||||
return;
|
||||
}
|
||||
}
|
||||
JLOG(m_journal.debug()) << "Updating paths";
|
||||
pathRequests.updateAll(lastLedger);
|
||||
|
||||
std::lock_guard ml(m_mutex);
|
||||
if (!pathRequests.requestsPending())
|
||||
{
|
||||
JLOG(m_journal.debug())
|
||||
<< "No path requests left. No need for further updating "
|
||||
"paths";
|
||||
--mPathFindThread;
|
||||
return;
|
||||
}
|
||||
app_.getPathRequests().updateAll(lastLedger);
|
||||
}
|
||||
catch (SHAMapMissingNode const& mn)
|
||||
{
|
||||
@@ -1622,12 +1587,8 @@ LedgerMaster::newPFWork(
|
||||
const char* name,
|
||||
std::unique_lock<std::recursive_mutex>&)
|
||||
{
|
||||
if (!app_.isStopping() && mPathFindThread < 2 &&
|
||||
app_.getPathRequests().requestsPending())
|
||||
if (mPathFindThread < 2)
|
||||
{
|
||||
JLOG(m_journal.debug())
|
||||
<< "newPFWork: Creating job. path find threads: "
|
||||
<< mPathFindThread;
|
||||
if (app_.getJobQueue().addJob(
|
||||
jtUPDATE_PF, name, [this]() { updatePaths(); }))
|
||||
{
|
||||
@@ -1662,7 +1623,7 @@ LedgerMaster::getValidatedLedger()
|
||||
#ifdef RIPPLED_REPORTING
|
||||
if (app_.config().reporting())
|
||||
{
|
||||
auto seq = app_.getRelationalDatabase().getMaxLedgerSeq();
|
||||
auto seq = app_.getRelationalDBInterface().getMaxLedgerSeq();
|
||||
if (!seq)
|
||||
return {};
|
||||
return getLedgerBySeq(*seq);
|
||||
@@ -1698,7 +1659,8 @@ LedgerMaster::getCompleteLedgers()
|
||||
{
|
||||
#ifdef RIPPLED_REPORTING
|
||||
if (app_.config().reporting())
|
||||
return static_cast<PostgresDatabase*>(&app_.getRelationalDatabase())
|
||||
return static_cast<RelationalDBInterfacePostgres*>(
|
||||
&app_.getRelationalDBInterface())
|
||||
->getCompleteLedgers();
|
||||
#endif
|
||||
std::lock_guard sl(mCompleteLock);
|
||||
@@ -1743,7 +1705,7 @@ LedgerMaster::getHashBySeq(std::uint32_t index)
|
||||
if (hash.isNonZero())
|
||||
return hash;
|
||||
|
||||
return app_.getRelationalDatabase().getHashByIndex(index);
|
||||
return app_.getRelationalDBInterface().getHashByIndex(index);
|
||||
}
|
||||
|
||||
std::optional<LedgerHash>
|
||||
@@ -1866,6 +1828,12 @@ LedgerMaster::setLedgerRangePresent(std::uint32_t minV, std::uint32_t maxV)
|
||||
mCompleteLedgers.insert(range(minV, maxV));
|
||||
}
|
||||
|
||||
void
|
||||
LedgerMaster::tune(int size, std::chrono::seconds age)
|
||||
{
|
||||
mLedgerHistory.tune(size, age);
|
||||
}
|
||||
|
||||
void
|
||||
LedgerMaster::sweep()
|
||||
{
|
||||
@@ -1964,7 +1932,7 @@ LedgerMaster::fetchForHistory(
|
||||
fillInProgress = mFillInProgress;
|
||||
}
|
||||
if (fillInProgress == 0 &&
|
||||
app_.getRelationalDatabase().getHashByIndex(seq - 1) ==
|
||||
app_.getRelationalDBInterface().getHashByIndex(seq - 1) ==
|
||||
ledger->info().parentHash)
|
||||
{
|
||||
{
|
||||
@@ -2106,7 +2074,7 @@ LedgerMaster::doAdvance(std::unique_lock<std::recursive_mutex>& sl)
|
||||
{
|
||||
JLOG(m_journal.trace()) << "tryAdvance found " << pubLedgers.size()
|
||||
<< " ledgers to publish";
|
||||
for (auto const& ledger : pubLedgers)
|
||||
for (auto ledger : pubLedgers)
|
||||
{
|
||||
{
|
||||
ScopedUnlock sul{sl};
|
||||
@@ -2360,7 +2328,7 @@ LedgerMaster::getFetchPackCacheSize() const
|
||||
std::optional<LedgerIndex>
|
||||
LedgerMaster::minSqlSeq()
|
||||
{
|
||||
return app_.getRelationalDatabase().getMinLedgerSeq();
|
||||
return app_.getRelationalDBInterface().getMinLedgerSeq();
|
||||
}
|
||||
|
||||
} // namespace ripple
|
||||
|
||||
@@ -65,7 +65,7 @@ TransactionAcquire::done()
|
||||
|
||||
if (failed_)
|
||||
{
|
||||
JLOG(journal_.debug()) << "Failed to acquire TX set " << hash_;
|
||||
JLOG(journal_.warn()) << "Failed to acquire TX set " << hash_;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -176,7 +176,8 @@ TransactionAcquire::trigger(std::shared_ptr<Peer> const& peer)
|
||||
|
||||
SHAMapAddNode
|
||||
TransactionAcquire::takeNodes(
|
||||
std::vector<std::pair<SHAMapNodeID, Slice>> const& data,
|
||||
const std::list<SHAMapNodeID>& nodeIDs,
|
||||
const std::list<Blob>& data,
|
||||
std::shared_ptr<Peer> const& peer)
|
||||
{
|
||||
ScopedLockType sl(mtx_);
|
||||
@@ -195,20 +196,24 @@ TransactionAcquire::takeNodes(
|
||||
|
||||
try
|
||||
{
|
||||
if (data.empty())
|
||||
if (nodeIDs.empty())
|
||||
return SHAMapAddNode::invalid();
|
||||
|
||||
std::list<SHAMapNodeID>::const_iterator nodeIDit = nodeIDs.begin();
|
||||
std::list<Blob>::const_iterator nodeDatait = data.begin();
|
||||
ConsensusTransSetSF sf(app_, app_.getTempNodeCache());
|
||||
|
||||
for (auto const& d : data)
|
||||
while (nodeIDit != nodeIDs.end())
|
||||
{
|
||||
if (d.first.isRoot())
|
||||
if (nodeIDit->isRoot())
|
||||
{
|
||||
if (mHaveRoot)
|
||||
JLOG(journal_.debug())
|
||||
<< "Got root TXS node, already have it";
|
||||
else if (!mMap->addRootNode(
|
||||
SHAMapHash{hash_}, d.second, nullptr)
|
||||
SHAMapHash{hash_},
|
||||
makeSlice(*nodeDatait),
|
||||
nullptr)
|
||||
.isGood())
|
||||
{
|
||||
JLOG(journal_.warn()) << "TX acquire got bad root node";
|
||||
@@ -216,22 +221,24 @@ TransactionAcquire::takeNodes(
|
||||
else
|
||||
mHaveRoot = true;
|
||||
}
|
||||
else if (!mMap->addKnownNode(d.first, d.second, &sf).isGood())
|
||||
else if (!mMap->addKnownNode(*nodeIDit, makeSlice(*nodeDatait), &sf)
|
||||
.isGood())
|
||||
{
|
||||
JLOG(journal_.warn()) << "TX acquire got bad non-root node";
|
||||
return SHAMapAddNode::invalid();
|
||||
}
|
||||
|
||||
++nodeIDit;
|
||||
++nodeDatait;
|
||||
}
|
||||
|
||||
trigger(peer);
|
||||
progress_ = true;
|
||||
return SHAMapAddNode::useful();
|
||||
}
|
||||
catch (std::exception const& ex)
|
||||
catch (std::exception const&)
|
||||
{
|
||||
JLOG(journal_.error())
|
||||
<< "Peer " << peer->id()
|
||||
<< " sent us junky transaction node data: " << ex.what();
|
||||
JLOG(journal_.error()) << "Peer sends us junky transaction node data";
|
||||
return SHAMapAddNode::invalid();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,8 @@ public:
|
||||
|
||||
SHAMapAddNode
|
||||
takeNodes(
|
||||
std::vector<std::pair<SHAMapNodeID, Slice>> const& data,
|
||||
const std::list<SHAMapNodeID>& IDs,
|
||||
const std::list<Blob>& data,
|
||||
std::shared_ptr<Peer> const&);
|
||||
|
||||
void
|
||||
|
||||
@@ -45,9 +45,10 @@
|
||||
#include <ripple/app/misc/ValidatorKeys.h>
|
||||
#include <ripple/app/misc/ValidatorSite.h>
|
||||
#include <ripple/app/paths/PathRequests.h>
|
||||
#include <ripple/app/rdb/Wallet.h>
|
||||
#include <ripple/app/rdb/backend/PostgresDatabase.h>
|
||||
#include <ripple/app/rdb/RelationalDBInterface_global.h>
|
||||
#include <ripple/app/rdb/backend/RelationalDBInterfacePostgres.h>
|
||||
#include <ripple/app/reporting/ReportingETL.h>
|
||||
#include <ripple/app/sidechain/Federator.h>
|
||||
#include <ripple/app/tx/apply.h>
|
||||
#include <ripple/basics/ByteUtilities.h>
|
||||
#include <ripple/basics/PerfLog.h>
|
||||
@@ -215,21 +216,21 @@ public:
|
||||
RCLValidations mValidations;
|
||||
std::unique_ptr<LoadManager> m_loadManager;
|
||||
std::unique_ptr<TxQ> txQ_;
|
||||
|
||||
std::shared_ptr<sidechain::Federator> sidechainFederator_;
|
||||
ClosureCounter<void, boost::system::error_code const&> waitHandlerCounter_;
|
||||
boost::asio::steady_timer sweepTimer_;
|
||||
boost::asio::steady_timer entropyTimer_;
|
||||
|
||||
std::unique_ptr<RelationalDatabase> mRelationalDatabase;
|
||||
std::unique_ptr<RelationalDBInterface> mRelationalDBInterface;
|
||||
std::unique_ptr<DatabaseCon> mWalletDB;
|
||||
std::unique_ptr<Overlay> overlay_;
|
||||
|
||||
boost::asio::signal_set m_signals;
|
||||
|
||||
// Once we get C++20, we could use `std::atomic_flag` for `isTimeToStop`
|
||||
// and eliminate the need for the condition variable and the mutex.
|
||||
std::condition_variable stoppingCondition_;
|
||||
mutable std::mutex stoppingMutex_;
|
||||
std::atomic<bool> isTimeToStop = false;
|
||||
std::condition_variable cv_;
|
||||
mutable std::mutex mut_;
|
||||
bool isTimeToStop = false;
|
||||
|
||||
std::atomic<bool> checkSigs_;
|
||||
|
||||
@@ -521,6 +522,8 @@ public:
|
||||
checkSigs(bool) override;
|
||||
bool
|
||||
isStopping() const override;
|
||||
void
|
||||
startFederator() override;
|
||||
int
|
||||
fdRequired() const override;
|
||||
|
||||
@@ -877,11 +880,11 @@ public:
|
||||
return *txQ_;
|
||||
}
|
||||
|
||||
RelationalDatabase&
|
||||
getRelationalDatabase() override
|
||||
RelationalDBInterface&
|
||||
getRelationalDBInterface() override
|
||||
{
|
||||
assert(mRelationalDatabase.get() != nullptr);
|
||||
return *mRelationalDatabase;
|
||||
assert(mRelationalDBInterface.get() != nullptr);
|
||||
return *mRelationalDBInterface;
|
||||
}
|
||||
|
||||
DatabaseCon&
|
||||
@@ -891,6 +894,12 @@ public:
|
||||
return *mWalletDB;
|
||||
}
|
||||
|
||||
std::shared_ptr<sidechain::Federator>
|
||||
getSidechainFederator() override
|
||||
{
|
||||
return sidechainFederator_;
|
||||
}
|
||||
|
||||
ReportingETL&
|
||||
getReportingETL() override
|
||||
{
|
||||
@@ -907,14 +916,14 @@ public:
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
bool
|
||||
initRelationalDatabase()
|
||||
initRDBMS()
|
||||
{
|
||||
assert(mWalletDB.get() == nullptr);
|
||||
|
||||
try
|
||||
{
|
||||
mRelationalDatabase =
|
||||
RelationalDatabase::init(*this, *config_, *m_jobQueue);
|
||||
mRelationalDBInterface =
|
||||
RelationalDBInterface::init(*this, *config_, *m_jobQueue);
|
||||
|
||||
// wallet database
|
||||
auto setup = setup_DatabaseCon(*config_, m_journal);
|
||||
@@ -962,9 +971,112 @@ public:
|
||||
<< "' took " << elapsed.count() << " seconds.";
|
||||
}
|
||||
|
||||
// tune caches
|
||||
using namespace std::chrono;
|
||||
|
||||
m_ledgerMaster->tune(
|
||||
config_->getValueFor(SizedItem::ledgerSize),
|
||||
seconds{config_->getValueFor(SizedItem::ledgerAge)});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
|
||||
// Called to indicate shutdown.
|
||||
void
|
||||
stop()
|
||||
{
|
||||
JLOG(m_journal.debug()) << "Application stopping";
|
||||
|
||||
m_io_latency_sampler.cancel_async();
|
||||
|
||||
// VFALCO Enormous hack, we have to force the probe to cancel
|
||||
// before we stop the io_service queue or else it never
|
||||
// unblocks in its destructor. The fix is to make all
|
||||
// io_objects gracefully handle exit so that we can
|
||||
// naturally return from io_service::run() instead of
|
||||
// forcing a call to io_service::stop()
|
||||
m_io_latency_sampler.cancel();
|
||||
|
||||
m_resolver->stop_async();
|
||||
|
||||
// NIKB This is a hack - we need to wait for the resolver to
|
||||
// stop. before we stop the io_server_queue or weird
|
||||
// things will happen.
|
||||
m_resolver->stop();
|
||||
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
sweepTimer_.cancel(ec);
|
||||
if (ec)
|
||||
{
|
||||
JLOG(m_journal.error())
|
||||
<< "Application: sweepTimer cancel error: " << ec.message();
|
||||
}
|
||||
|
||||
ec.clear();
|
||||
entropyTimer_.cancel(ec);
|
||||
if (ec)
|
||||
{
|
||||
JLOG(m_journal.error())
|
||||
<< "Application: entropyTimer cancel error: "
|
||||
<< ec.message();
|
||||
}
|
||||
}
|
||||
// Make sure that any waitHandlers pending in our timers are done
|
||||
// before we declare ourselves stopped.
|
||||
using namespace std::chrono_literals;
|
||||
waitHandlerCounter_.join("Application", 1s, m_journal);
|
||||
|
||||
mValidations.flush();
|
||||
|
||||
validatorSites_->stop();
|
||||
|
||||
// TODO Store manifests in manifests.sqlite instead of wallet.db
|
||||
validatorManifests_->save(
|
||||
getWalletDB(),
|
||||
"ValidatorManifests",
|
||||
[this](PublicKey const& pubKey) {
|
||||
return validators().listed(pubKey);
|
||||
});
|
||||
|
||||
publisherManifests_->save(
|
||||
getWalletDB(),
|
||||
"PublisherManifests",
|
||||
[this](PublicKey const& pubKey) {
|
||||
return validators().trustedPublisher(pubKey);
|
||||
});
|
||||
|
||||
// The order of these stop calls is delicate.
|
||||
// Re-ordering them risks undefined behavior.
|
||||
m_loadManager->stop();
|
||||
m_shaMapStore->stop();
|
||||
m_jobQueue->stop();
|
||||
if (shardArchiveHandler_)
|
||||
shardArchiveHandler_->stop();
|
||||
if (overlay_)
|
||||
overlay_->stop();
|
||||
if (shardStore_)
|
||||
shardStore_->stop();
|
||||
grpcServer_->stop();
|
||||
m_networkOPs->stop();
|
||||
serverHandler_->stop();
|
||||
m_ledgerReplayer->stop();
|
||||
m_inboundTransactions->stop();
|
||||
m_inboundLedgers->stop();
|
||||
ledgerCleaner_->stop();
|
||||
if (reportingETL_)
|
||||
reportingETL_->stop();
|
||||
if (sidechainFederator_)
|
||||
sidechainFederator_->stop();
|
||||
if (auto pg = dynamic_cast<RelationalDBInterfacePostgres*>(
|
||||
&*mRelationalDBInterface))
|
||||
pg->stop();
|
||||
m_nodeStore->stop();
|
||||
perfLog_->stop();
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------
|
||||
//
|
||||
// PropertyStream
|
||||
@@ -1041,7 +1153,7 @@ public:
|
||||
doSweep()
|
||||
{
|
||||
if (!config_->standalone() &&
|
||||
!getRelationalDatabase().transactionDbHasSpace(*config_))
|
||||
!getRelationalDBInterface().transactionDbHasSpace(*config_))
|
||||
{
|
||||
signalStop();
|
||||
}
|
||||
@@ -1064,9 +1176,12 @@ public:
|
||||
getLedgerReplayer().sweep();
|
||||
m_acceptedLedgerCache.sweep();
|
||||
cachedSLEs_.sweep();
|
||||
if (sidechainFederator_)
|
||||
sidechainFederator_->sweep();
|
||||
|
||||
#ifdef RIPPLED_REPORTING
|
||||
if (auto pg = dynamic_cast<PostgresDatabase*>(&*mRelationalDatabase))
|
||||
if (auto pg = dynamic_cast<RelationalDBInterfacePostgres*>(
|
||||
&*mRelationalDBInterface))
|
||||
pg->sweep();
|
||||
#endif
|
||||
|
||||
@@ -1161,7 +1276,7 @@ ApplicationImp::setup()
|
||||
if (!config_->standalone())
|
||||
timeKeeper_->run(config_->SNTP_SERVERS);
|
||||
|
||||
if (!initRelationalDatabase() || !initNodeStore())
|
||||
if (!initRDBMS() || !initNodeStore())
|
||||
return false;
|
||||
|
||||
if (shardStore_)
|
||||
@@ -1497,6 +1612,15 @@ ApplicationImp::setup()
|
||||
if (reportingETL_)
|
||||
reportingETL_->start();
|
||||
|
||||
sidechainFederator_ = sidechain::make_Federator(
|
||||
*this,
|
||||
get_io_service(),
|
||||
*config_,
|
||||
logs_->journal("SidechainFederator"));
|
||||
|
||||
if (sidechainFederator_)
|
||||
sidechainFederator_->start();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1521,6 +1645,7 @@ ApplicationImp::start(bool withTimers)
|
||||
grpcServer_->start();
|
||||
ledgerCleaner_->start();
|
||||
perfLog_->start();
|
||||
startFederator();
|
||||
}
|
||||
|
||||
void
|
||||
@@ -1536,101 +1661,27 @@ ApplicationImp::run()
|
||||
}
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lk{stoppingMutex_};
|
||||
stoppingCondition_.wait(lk, [this] { return isTimeToStop.load(); });
|
||||
std::unique_lock<std::mutex> lk{mut_};
|
||||
cv_.wait(lk, [this] { return isTimeToStop; });
|
||||
}
|
||||
|
||||
JLOG(m_journal.debug()) << "Application stopping";
|
||||
|
||||
m_io_latency_sampler.cancel_async();
|
||||
|
||||
// VFALCO Enormous hack, we have to force the probe to cancel
|
||||
// before we stop the io_service queue or else it never
|
||||
// unblocks in its destructor. The fix is to make all
|
||||
// io_objects gracefully handle exit so that we can
|
||||
// naturally return from io_service::run() instead of
|
||||
// forcing a call to io_service::stop()
|
||||
m_io_latency_sampler.cancel();
|
||||
|
||||
m_resolver->stop_async();
|
||||
|
||||
// NIKB This is a hack - we need to wait for the resolver to
|
||||
// stop. before we stop the io_server_queue or weird
|
||||
// things will happen.
|
||||
m_resolver->stop();
|
||||
|
||||
{
|
||||
boost::system::error_code ec;
|
||||
sweepTimer_.cancel(ec);
|
||||
if (ec)
|
||||
{
|
||||
JLOG(m_journal.error())
|
||||
<< "Application: sweepTimer cancel error: " << ec.message();
|
||||
}
|
||||
|
||||
ec.clear();
|
||||
entropyTimer_.cancel(ec);
|
||||
if (ec)
|
||||
{
|
||||
JLOG(m_journal.error())
|
||||
<< "Application: entropyTimer cancel error: " << ec.message();
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure that any waitHandlers pending in our timers are done
|
||||
// before we declare ourselves stopped.
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
waitHandlerCounter_.join("Application", 1s, m_journal);
|
||||
|
||||
mValidations.flush();
|
||||
|
||||
validatorSites_->stop();
|
||||
|
||||
// TODO Store manifests in manifests.sqlite instead of wallet.db
|
||||
validatorManifests_->save(
|
||||
getWalletDB(), "ValidatorManifests", [this](PublicKey const& pubKey) {
|
||||
return validators().listed(pubKey);
|
||||
});
|
||||
|
||||
publisherManifests_->save(
|
||||
getWalletDB(), "PublisherManifests", [this](PublicKey const& pubKey) {
|
||||
return validators().trustedPublisher(pubKey);
|
||||
});
|
||||
|
||||
// The order of these stop calls is delicate.
|
||||
// Re-ordering them risks undefined behavior.
|
||||
m_loadManager->stop();
|
||||
m_shaMapStore->stop();
|
||||
m_jobQueue->stop();
|
||||
if (shardArchiveHandler_)
|
||||
shardArchiveHandler_->stop();
|
||||
if (overlay_)
|
||||
overlay_->stop();
|
||||
if (shardStore_)
|
||||
shardStore_->stop();
|
||||
grpcServer_->stop();
|
||||
m_networkOPs->stop();
|
||||
serverHandler_->stop();
|
||||
m_ledgerReplayer->stop();
|
||||
m_inboundTransactions->stop();
|
||||
m_inboundLedgers->stop();
|
||||
ledgerCleaner_->stop();
|
||||
if (reportingETL_)
|
||||
reportingETL_->stop();
|
||||
if (auto pg = dynamic_cast<PostgresDatabase*>(&*mRelationalDatabase))
|
||||
pg->stop();
|
||||
m_nodeStore->stop();
|
||||
perfLog_->stop();
|
||||
|
||||
JLOG(m_journal.info()) << "Received shutdown request";
|
||||
stop();
|
||||
JLOG(m_journal.info()) << "Done.";
|
||||
}
|
||||
|
||||
void
|
||||
ApplicationImp::signalStop()
|
||||
{
|
||||
if (!isTimeToStop.exchange(true))
|
||||
stoppingCondition_.notify_all();
|
||||
// Unblock the main thread (which is sitting in run()).
|
||||
// When we get C++20 this can use std::latch.
|
||||
std::lock_guard lk{mut_};
|
||||
|
||||
if (!isTimeToStop)
|
||||
{
|
||||
isTimeToStop = true;
|
||||
cv_.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
bool
|
||||
@@ -1648,7 +1699,16 @@ ApplicationImp::checkSigs(bool check)
|
||||
bool
|
||||
ApplicationImp::isStopping() const
|
||||
{
|
||||
return isTimeToStop.load();
|
||||
std::lock_guard lk{mut_};
|
||||
return isTimeToStop;
|
||||
}
|
||||
|
||||
void
|
||||
ApplicationImp::startFederator()
|
||||
{
|
||||
if (sidechainFederator_)
|
||||
sidechainFederator_->unlockMainLoop(
|
||||
sidechain::Federator::UnlockMainLoopKey::app);
|
||||
}
|
||||
|
||||
int
|
||||
@@ -2135,7 +2195,7 @@ ApplicationImp::nodeToShards()
|
||||
void
|
||||
ApplicationImp::setMaxDisallowedLedger()
|
||||
{
|
||||
auto seq = getRelationalDatabase().getMaxLedgerSeq();
|
||||
auto seq = getRelationalDBInterface().getMaxLedgerSeq();
|
||||
if (seq)
|
||||
maxDisallowedLedger_ = *seq;
|
||||
|
||||
|
||||
@@ -50,6 +50,10 @@ namespace RPC {
|
||||
class ShardArchiveHandler;
|
||||
}
|
||||
|
||||
namespace sidechain {
|
||||
class Federator;
|
||||
}
|
||||
|
||||
// VFALCO TODO Fix forward declares required for header dependency loops
|
||||
class AmendmentTable;
|
||||
|
||||
@@ -99,7 +103,7 @@ class ValidatorList;
|
||||
class ValidatorSite;
|
||||
class Cluster;
|
||||
|
||||
class RelationalDatabase;
|
||||
class RelationalDBInterface;
|
||||
class DatabaseCon;
|
||||
class SHAMapStore;
|
||||
|
||||
@@ -150,6 +154,9 @@ public:
|
||||
virtual bool
|
||||
isStopping() const = 0;
|
||||
|
||||
virtual void
|
||||
startFederator() = 0;
|
||||
|
||||
//
|
||||
// ---
|
||||
//
|
||||
@@ -251,8 +258,8 @@ public:
|
||||
openLedger() = 0;
|
||||
virtual OpenLedger const&
|
||||
openLedger() const = 0;
|
||||
virtual RelationalDatabase&
|
||||
getRelationalDatabase() = 0;
|
||||
virtual RelationalDBInterface&
|
||||
getRelationalDBInterface() = 0;
|
||||
|
||||
virtual std::chrono::milliseconds
|
||||
getIOLatency() = 0;
|
||||
@@ -274,6 +281,9 @@ public:
|
||||
virtual DatabaseCon&
|
||||
getWalletDB() = 0;
|
||||
|
||||
virtual std::shared_ptr<sidechain::Federator>
|
||||
getSidechainFederator() = 0;
|
||||
|
||||
/** Ensure that a newly-started validator does not sign proposals older
|
||||
* than the last ledger it persisted. */
|
||||
virtual LedgerIndex
|
||||
|
||||
@@ -72,22 +72,12 @@ inline constexpr std::array<char const*, 5> LgrDBInit{
|
||||
// Transaction database holds transactions and public keys
|
||||
inline constexpr auto TxDBName{"transaction.db"};
|
||||
|
||||
// In C++17 omitting the explicit template parameters caused
|
||||
// a crash
|
||||
inline constexpr std::array<char const*, 4> TxDBPragma
|
||||
inline constexpr std::array TxDBPragma
|
||||
{
|
||||
"PRAGMA page_size=4096;", "PRAGMA journal_size_limit=1582080;",
|
||||
"PRAGMA max_page_count=2147483646;",
|
||||
|
||||
#if (ULONG_MAX > UINT_MAX) && !defined(NO_SQLITE_MMAP)
|
||||
"PRAGMA mmap_size=17179869184;"
|
||||
#else
|
||||
|
||||
// Provide an explicit `no-op` SQL statement
|
||||
// in order to keep the size of the array
|
||||
// constant regardless of the preprocessor
|
||||
// condition evaluation
|
||||
"PRAGMA sqlite_noop_statement;"
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -127,22 +117,12 @@ inline constexpr std::array<char const*, 8> TxDBInit{
|
||||
// The Ledger Meta database maps ledger hashes to shard indexes
|
||||
inline constexpr auto LgrMetaDBName{"ledger_meta.db"};
|
||||
|
||||
// In C++17 omitting the explicit template parameters caused
|
||||
// a crash
|
||||
inline constexpr std::array<char const*, 4> LgrMetaDBPragma
|
||||
inline constexpr std::array LgrMetaDBPragma
|
||||
{
|
||||
"PRAGMA page_size=4096;", "PRAGMA journal_size_limit=1582080;",
|
||||
"PRAGMA max_page_count=2147483646;",
|
||||
|
||||
#if (ULONG_MAX > UINT_MAX) && !defined(NO_SQLITE_MMAP)
|
||||
"PRAGMA mmap_size=17179869184;"
|
||||
#else
|
||||
|
||||
// Provide an explicit `no-op` SQL statement
|
||||
// in order to keep the size of the array
|
||||
// constant regardless of the preprocessor
|
||||
// condition evaluation
|
||||
"PRAGMA sqlite_noop_statement;"
|
||||
#endif
|
||||
};
|
||||
|
||||
@@ -161,22 +141,12 @@ inline constexpr std::array<char const*, 3> LgrMetaDBInit{
|
||||
// Transaction Meta database maps transaction IDs to shard indexes
|
||||
inline constexpr auto TxMetaDBName{"transaction_meta.db"};
|
||||
|
||||
// In C++17 omitting the explicit template parameters caused
|
||||
// a crash
|
||||
inline constexpr std::array<char const*, 4> TxMetaDBPragma
|
||||
inline constexpr std::array TxMetaDBPragma
|
||||
{
|
||||
"PRAGMA page_size=4096;", "PRAGMA journal_size_limit=1582080;",
|
||||
"PRAGMA max_page_count=2147483646;",
|
||||
|
||||
#if (ULONG_MAX > UINT_MAX) && !defined(NO_SQLITE_MMAP)
|
||||
"PRAGMA mmap_size=17179869184;"
|
||||
#else
|
||||
|
||||
// Provide an explicit `no-op` SQL statement
|
||||
// in order to keep the size of the array
|
||||
// constant regardless of the preprocessor
|
||||
// condition evaluation
|
||||
"PRAGMA sqlite_noop_statement;"
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
|
||||
#include <ripple/app/main/Application.h>
|
||||
#include <ripple/app/main/DBInit.h>
|
||||
#include <ripple/app/rdb/Vacuum.h>
|
||||
#include <ripple/app/rdb/RelationalDBInterface_global.h>
|
||||
#include <ripple/app/sidechain/Federator.h>
|
||||
#include <ripple/basics/Log.h>
|
||||
#include <ripple/basics/StringUtilities.h>
|
||||
#include <ripple/basics/contract.h>
|
||||
@@ -135,7 +136,6 @@ printHelp(const po::options_description& desc)
|
||||
"[strict]\n"
|
||||
" account_tx accountID [ledger_min [ledger_max [limit "
|
||||
"[offset]]]] [binary] [count] [descending]\n"
|
||||
" book_changes [<ledger hash|id>]\n"
|
||||
" book_offers <taker_pays> <taker_gets> [<taker [<ledger> "
|
||||
"[<limit> [<proof> [<marker>]]]]]\n"
|
||||
" can_delete [<ledgerid>|<ledgerhash>|now|always|never]\n"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user