From fcb87b635c027b84fb31c0ccceb9653fb737446b Mon Sep 17 00:00:00 2001 From: Ludo Galabru Date: Wed, 27 May 2020 21:49:13 -0400 Subject: [PATCH] Genesis --- .cargo/config | 2 + .dockerignore | 9 + .gitattributes | 11 + .github/workflows/ci.yaml | 731 ++ .github/workflows/new-issues.yaml | 16 + .github/workflows/pkg-version-bump.yaml | 64 + .gitignore | 25 + CHANGELOG.md | 30 + Cargo.lock | 8079 +++++++++++++++++ Cargo.toml | 8 + LICENSE | 674 ++ README.md | 816 ++ components/chainhook-cli/Cargo.toml | 45 + components/chainhook-cli/Chainhook.toml | 14 + components/chainhook-cli/README.md | 207 + .../chainhook-cli/benches/codec/clarity.rs | 28 + components/chainhook-cli/benches/codec/hex.rs | 398 + .../chainhook-cli/benches/storage/redis.rs | 17 + .../chainhook-cli/benches/storage/rocksdb.rs | 16 + .../chainhook-cli/benches/storage/sqlite.rs | 16 + .../examples/arkadiko-data-indexing/README.md | 61 + .../vault-monitor/.gitattributes | 7 + .../vault-monitor/.gitignore | 35 + .../vault-monitor/.ruby-version | 1 + .../vault-monitor/Gemfile | 77 + .../vault-monitor/Gemfile.lock | 287 + .../vault-monitor/README.md | 19 + .../vault-monitor/Rakefile | 6 + .../app/assets/config/manifest.js | 4 + .../vault-monitor/app/assets/images/.keep | 0 .../app/assets/stylesheets/application.css | 15 + .../app/chainhooks/observe_vaults.json | 23 + .../app/channels/application_cable/channel.rb | 4 + .../channels/application_cable/connection.rb | 4 + .../admin/application_controller.rb | 21 + .../controllers/admin/vaults_controller.rb | 47 + .../app/controllers/application_controller.rb | 2 + .../app/controllers/chainhooks_controller.rb | 28 + .../app/controllers/concerns/.keep | 0 .../app/controllers/vaults_controller.rb | 70 + .../app/dashboards/vault_dashboard.rb | 122 + .../app/helpers/application_helper.rb | 2 + .../app/helpers/vaults_helper.rb | 2 + .../app/javascript/application.js | 3 + .../app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + .../app/javascript/controllers/index.js | 11 + .../vault-monitor/app/jobs/application_job.rb | 7 + .../app/mailers/application_mailer.rb | 4 + .../app/models/application_record.rb | 3 + .../vault-monitor/app/models/concerns/.keep | 0 .../vault-monitor/app/models/vault.rb | 48 + .../views/admin/vaults/_collection.html.erb | 76 + .../app/views/admin/vaults/index.html.erb | 21 + .../app/views/admin/vaults/show.html.erb | 23 + .../app/views/layouts/application.html.erb | 16 + .../app/views/layouts/mailer.html.erb | 13 + .../app/views/layouts/mailer.text.erb | 1 + .../app/views/vaults/_form.html.erb | 102 + .../app/views/vaults/_vault.html.erb | 87 + .../app/views/vaults/_vault.json.jbuilder | 2 + .../app/views/vaults/edit.html.erb | 10 + .../app/views/vaults/index.html.erb | 14 + .../app/views/vaults/index.json.jbuilder | 1 + .../app/views/vaults/new.html.erb | 9 + .../app/views/vaults/show.html.erb | 10 + .../app/views/vaults/show.json.jbuilder | 1 + .../vault-monitor/bin/bundle | 114 + .../vault-monitor/bin/importmap | 4 + .../vault-monitor/bin/rails | 4 + .../vault-monitor/bin/rake | 4 + .../vault-monitor/bin/setup | 33 + .../vault-monitor/config.ru | 6 + .../vault-monitor/config/application.rb | 26 + .../vault-monitor/config/boot.rb | 4 + .../vault-monitor/config/cable.yml | 11 + .../vault-monitor/config/credentials.yml.enc | 1 + .../vault-monitor/config/database.yml | 25 + .../vault-monitor/config/environment.rb | 5 + .../config/environments/development.rb | 76 + .../config/environments/production.rb | 99 + .../vault-monitor/config/environments/test.rb | 60 + .../vault-monitor/config/importmap.rb | 7 + .../config/initializers/assets.rb | 12 + .../initializers/content_security_policy.rb | 25 + .../initializers/filter_parameter_logging.rb | 8 + .../config/initializers/inflections.rb | 16 + .../config/initializers/permissions_policy.rb | 11 + .../vault-monitor/config/locales/en.yml | 33 + .../vault-monitor/config/logging.rb | 113 + .../vault-monitor/config/puma.rb | 43 + .../vault-monitor/config/routes.rb | 8 + .../vault-monitor/config/storage.yml | 34 + .../migrate/20220817092514_create_vaults.rb | 25 + .../vault-monitor/db/schema.rb | 36 + .../vault-monitor/db/seeds.rb | 7 + .../vault-monitor/lib/assets/.keep | 0 .../vault-monitor/lib/tasks/.keep | 0 .../vault-monitor/log/.keep | 0 .../vault-monitor/public/404.html | 67 + .../vault-monitor/public/422.html | 67 + .../vault-monitor/public/500.html | 66 + .../public/apple-touch-icon-precomposed.png | 0 .../vault-monitor/public/apple-touch-icon.png | 0 .../vault-monitor/public/favicon.ico | 0 .../vault-monitor/public/robots.txt | 1 + .../vault-monitor/storage/.keep | 0 .../test/application_system_test_case.rb | 5 + .../application_cable/connection_test.rb | 11 + .../vault-monitor/test/controllers/.keep | 0 .../controllers/vaults_controller_test.rb | 48 + .../vault-monitor/test/fixtures/files/.keep | 0 .../vault-monitor/test/fixtures/vaults.yml | 39 + .../vault-monitor/test/helpers/.keep | 0 .../vault-monitor/test/integration/.keep | 0 .../vault-monitor/test/mailers/.keep | 0 .../vault-monitor/test/models/.keep | 0 .../vault-monitor/test/models/vault_test.rb | 7 + .../vault-monitor/test/system/.keep | 0 .../vault-monitor/test/system/vaults_test.rb | 73 + .../vault-monitor/test/test_helper.rb | 13 + components/chainhook-cli/src/archive/mod.rs | 85 + .../chainhook-cli/src/block/digestion.rs | 147 + .../chainhook-cli/src/block/ingestion.rs | 234 + components/chainhook-cli/src/block/mod.rs | 11 + components/chainhook-cli/src/cli/mod.rs | 1182 +++ components/chainhook-cli/src/config/file.rs | 38 + components/chainhook-cli/src/config/mod.rs | 302 + components/chainhook-cli/src/main.rs | 19 + .../chainhook-event-observer/Cargo.lock | 3929 ++++++++ .../chainhook-event-observer/Cargo.toml | 40 + .../chainhook-event-observer/Observer.toml | 14 + .../chainhook-event-observer/doc/openapi.json | 682 ++ .../src/chainhooks/bitcoin/mod.rs | 398 + .../src/chainhooks/mod.rs | 3 + .../src/chainhooks/stacks/mod.rs | 694 ++ .../src/chainhooks/types.rs | 1064 +++ .../src/indexer/bitcoin/blocks_pool.rs | 366 + .../src/indexer/bitcoin/mod.rs | 309 + .../src/indexer/bitcoin/tests.rs | 206 + .../src/indexer/mod.rs | 385 + .../src/indexer/stacks/blocks_pool.rs | 1018 +++ .../src/indexer/stacks/mod.rs | 1094 +++ .../src/indexer/stacks/tests.rs | 256 + .../src/indexer/tests/helpers/accounts.rs | 79 + .../indexer/tests/helpers/bitcoin_blocks.rs | 140 + .../indexer/tests/helpers/bitcoin_shapes.rs | 2652 ++++++ .../src/indexer/tests/helpers/microblocks.rs | 154 + .../src/indexer/tests/helpers/mod.rs | 25 + .../indexer/tests/helpers/stacks_blocks.rs | 191 + .../indexer/tests/helpers/stacks_shapes.rs | 3494 +++++++ .../src/indexer/tests/helpers/transactions.rs | 111 + .../src/indexer/tests/mod.rs | 44 + .../chainhook-event-observer/src/lib.rs | 18 + .../chainhook-event-observer/src/main.rs | 175 + .../src/observer/mod.rs | 1535 ++++ .../src/observer/tests/mod.rs | 990 ++ .../chainhook-event-observer/src/utils/mod.rs | 120 + components/chainhook-types-js/package.json | 12 + components/chainhook-types-js/src/index.ts | 1081 +++ components/chainhook-types-js/tsconfig.json | 100 + components/chainhook-types-rs/Cargo.toml | 13 + components/chainhook-types-rs/src/bitcoin.rs | 66 + components/chainhook-types-rs/src/events.rs | 142 + components/chainhook-types-rs/src/lib.rs | 16 + .../src/proto/messages.proto | 94 + components/chainhook-types-rs/src/rosetta.rs | 700 ++ components/hiro-system-kit/Cargo.toml | 33 + components/hiro-system-kit/src/lib.rs | 34 + components/hiro-system-kit/src/log/mod.rs | 25 + components/hiro-system-kit/src/macros.rs | 167 + .../hiro-system-kit/src/tokio_helpers.rs | 23 + .../chainhook-event-observer.dockerfile | 37 + .../components/chainhook-node.dockerfile | 39 + rust-toolchain | 2 + wix/License.rtf | 180 + wix/main.wxs | 182 + 177 files changed, 38918 insertions(+) create mode 100644 .cargo/config create mode 100644 .dockerignore create mode 100644 .gitattributes create mode 100644 .github/workflows/ci.yaml create mode 100644 .github/workflows/new-issues.yaml create mode 100644 .github/workflows/pkg-version-bump.yaml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 components/chainhook-cli/Cargo.toml create mode 100644 components/chainhook-cli/Chainhook.toml create mode 100644 components/chainhook-cli/README.md create mode 100644 components/chainhook-cli/benches/codec/clarity.rs create mode 100644 components/chainhook-cli/benches/codec/hex.rs create mode 100644 components/chainhook-cli/benches/storage/redis.rs create mode 100644 components/chainhook-cli/benches/storage/rocksdb.rs create mode 100644 components/chainhook-cli/benches/storage/sqlite.rs create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/README.md create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitattributes create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitignore create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.ruby-version create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile.lock create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/README.md create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Rakefile create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/config/manifest.js create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/images/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/stylesheets/application.css create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/chainhooks/observe_vaults.json create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/channel.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/connection.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/application_controller.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/vaults_controller.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/application_controller.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/chainhooks_controller.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/concerns/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/vaults_controller.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/dashboards/vault_dashboard.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/application_helper.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/vaults_helper.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/application.js create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/application.js create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/hello_controller.js create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/index.js create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/jobs/application_job.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/mailers/application_mailer.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/application_record.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/concerns/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/vault.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/_collection.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/index.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/show.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/application.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.text.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_form.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.json.jbuilder create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/edit.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.json.jbuilder create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/new.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.html.erb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.json.jbuilder create mode 100755 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/bundle create mode 100755 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/importmap create mode 100755 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rails create mode 100755 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rake create mode 100755 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/setup create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config.ru create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/application.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/boot.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/cable.yml create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/credentials.yml.enc create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/database.yml create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environment.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/development.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/production.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/test.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/importmap.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/assets.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/content_security_policy.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/filter_parameter_logging.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/inflections.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/permissions_policy.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/locales/en.yml create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/logging.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/puma.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/routes.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/storage.yml create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/migrate/20220817092514_create_vaults.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/schema.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/seeds.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/lib/assets/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/lib/tasks/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/log/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/404.html create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/422.html create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/500.html create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/apple-touch-icon-precomposed.png create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/apple-touch-icon.png create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/favicon.ico create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/robots.txt create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/storage/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/application_system_test_case.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/channels/application_cable/connection_test.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/vaults_controller_test.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/files/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/vaults.yml create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/helpers/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/integration/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/mailers/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/vault_test.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/.keep create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/vaults_test.rb create mode 100644 components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/test_helper.rb create mode 100644 components/chainhook-cli/src/archive/mod.rs create mode 100644 components/chainhook-cli/src/block/digestion.rs create mode 100644 components/chainhook-cli/src/block/ingestion.rs create mode 100644 components/chainhook-cli/src/block/mod.rs create mode 100644 components/chainhook-cli/src/cli/mod.rs create mode 100644 components/chainhook-cli/src/config/file.rs create mode 100644 components/chainhook-cli/src/config/mod.rs create mode 100644 components/chainhook-cli/src/main.rs create mode 100644 components/chainhook-event-observer/Cargo.lock create mode 100644 components/chainhook-event-observer/Cargo.toml create mode 100644 components/chainhook-event-observer/Observer.toml create mode 100644 components/chainhook-event-observer/doc/openapi.json create mode 100644 components/chainhook-event-observer/src/chainhooks/bitcoin/mod.rs create mode 100644 components/chainhook-event-observer/src/chainhooks/mod.rs create mode 100644 components/chainhook-event-observer/src/chainhooks/stacks/mod.rs create mode 100644 components/chainhook-event-observer/src/chainhooks/types.rs create mode 100644 components/chainhook-event-observer/src/indexer/bitcoin/blocks_pool.rs create mode 100644 components/chainhook-event-observer/src/indexer/bitcoin/mod.rs create mode 100644 components/chainhook-event-observer/src/indexer/bitcoin/tests.rs create mode 100644 components/chainhook-event-observer/src/indexer/mod.rs create mode 100644 components/chainhook-event-observer/src/indexer/stacks/blocks_pool.rs create mode 100644 components/chainhook-event-observer/src/indexer/stacks/mod.rs create mode 100644 components/chainhook-event-observer/src/indexer/stacks/tests.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/accounts.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_blocks.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_shapes.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/microblocks.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/mod.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/stacks_blocks.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/stacks_shapes.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/helpers/transactions.rs create mode 100644 components/chainhook-event-observer/src/indexer/tests/mod.rs create mode 100644 components/chainhook-event-observer/src/lib.rs create mode 100644 components/chainhook-event-observer/src/main.rs create mode 100644 components/chainhook-event-observer/src/observer/mod.rs create mode 100644 components/chainhook-event-observer/src/observer/tests/mod.rs create mode 100644 components/chainhook-event-observer/src/utils/mod.rs create mode 100644 components/chainhook-types-js/package.json create mode 100644 components/chainhook-types-js/src/index.ts create mode 100644 components/chainhook-types-js/tsconfig.json create mode 100644 components/chainhook-types-rs/Cargo.toml create mode 100644 components/chainhook-types-rs/src/bitcoin.rs create mode 100644 components/chainhook-types-rs/src/events.rs create mode 100644 components/chainhook-types-rs/src/lib.rs create mode 100644 components/chainhook-types-rs/src/proto/messages.proto create mode 100644 components/chainhook-types-rs/src/rosetta.rs create mode 100644 components/hiro-system-kit/Cargo.toml create mode 100644 components/hiro-system-kit/src/lib.rs create mode 100644 components/hiro-system-kit/src/log/mod.rs create mode 100644 components/hiro-system-kit/src/macros.rs create mode 100644 components/hiro-system-kit/src/tokio_helpers.rs create mode 100644 dockerfiles/components/chainhook-event-observer.dockerfile create mode 100644 dockerfiles/components/chainhook-node.dockerfile create mode 100644 rust-toolchain create mode 100644 wix/License.rtf create mode 100644 wix/main.wxs diff --git a/.cargo/config b/.cargo/config new file mode 100644 index 0000000..df6388b --- /dev/null +++ b/.cargo/config @@ -0,0 +1,2 @@ +[alias] +chainhook-install = "install --path components/chainhook-cli --locked --force" diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..285feb9 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +target/ +examples/ +dockerfiles/ +Dockerfile +.dockerignore +.git* +node_modules +package-lock.json +*.tar.gz diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..d0f9485 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# Have linguist ignore typescript compiler sources +components/clarinet-cli/js/* linguist-vendored +components/clarinet-cli/dts/* linguist-vendored +components/clarinet-cli/tsc/* linguist-vendored + +# Declare Clarity files that will always have LF line endings on checkout. +*.clar text eol=lf + +# Denote all files that are truly binary and should not be modified. +*.png binary +*.jpg binary diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..947156b --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,731 @@ +name: CI +on: + pull_request: + push: + branches: + - main + - develop + - rc/next + workflow_dispatch: + +jobs: + pre_run: + name: Cancel previous runs + runs-on: ubuntu-latest + steps: + - name: Cancel Previous Runs + uses: styfle/cancel-workflow-action@ad6cb1b847ffb509a69b745b6ee2f1d14dfe14b8 + with: + access_token: ${{ github.token }} + persist-credentials: false + + get_release_info: + name: Get Release Info + runs-on: ubuntu-latest + needs: pre_run + outputs: + tag: ${{ steps.new_release_tag.outputs.TAG }} + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Get latest release + if: startsWith(github.ref, 'refs/heads/main') + id: release + uses: pozetroninc/github-action-get-latest-release@master + with: + repository: ${{ github.repository }} + excludes: prerelease, draft + + - name: Determine if release build + if: startsWith(github.ref, 'refs/heads/main') + id: new_release_tag + env: + LATEST_RELEASE: ${{ steps.release.outputs.release }} + run: | + CARGO_VERSION=v$(grep "version" components/clarinet-cli/Cargo.toml | head -n 1 | cut -d\" -f2) + if [[ "${CARGO_VERSION}" != "${LATEST_RELEASE}" ]]; then + echo "::set-output name=TAG::${CARGO_VERSION}" + echo "::warning::Will create release for version: ${CARGO_VERSION}" + else + echo "::warning::Will not create a release" + fi + + audit: + name: Audit and format + runs-on: ubuntu-latest + needs: pre_run + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + profile: minimal + components: rustfmt + override: true + + - name: Set Cargo file permissions + run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/ + + - name: Cache cargo + uses: actions/cache@v2 + with: + path: ~/.cargo/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + - name: Install dependencies + run: cargo install cargo-audit + + - name: Run audit + run: cargo audit --ignore RUSTSEC-2021-0076 --ignore RUSTSEC-2021-0119 --ignore RUSTSEC-2022-0028 --ignore RUSTSEC-2020-0071 --ignore RUSTSEC-2021-0124 --ignore RUSTSEC-2022-0040 + + - name: Run rustfmt + run: cargo fmt --all -- --check + + # test_coverage_cargo: + # name: Generate test coverage + # runs-on: ubuntu-latest + # needs: pre_run + # strategy: + # fail-fast: false + # matrix: + # include: + # - name: clarinet + # working-directory: components/clarinet-cli + # - name: clarity-repl + # working-directory: components/clarity-repl + # - name: chainhook-cli + # working-directory: components/chainhook-event-observer + # steps: + # - name: Checkout repository + # uses: actions/checkout@v3 + # with: + # submodules: recursive + + # - name: Install Rust toolchain stable + # uses: actions-rs/toolchain@v1 + # with: + # toolchain: stable + # profile: minimal + # override: true + + # - name: Cache cargo + # uses: actions/cache@v2 + # id: cache-cargo + # with: + # path: | + # ~/.cargo/bin/ + # ~/.cargo/registry/index/ + # ~/.cargo/registry/cache/ + # ~/.cargo/git/db/ + # target/ + # key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + # - name: Install dependencies + # if: steps.cache-cargo.outputs.cache-hit != 'true' + # run: RUSTC_BOOTSTRAP=1 cargo install grcov + + # - name: Install Rust toolchain + # uses: actions-rs/toolchain@v1 + # with: + # toolchain: stable + # profile: minimal + # components: llvm-tools-preview + # override: true + + # - name: Unit Tests + # env: + # RUSTFLAGS: "-C instrument-coverage" + # LLVM_PROFILE_FILE: "${{ matrix.name }}-%p-%m.profraw" + # run: cargo build --package=clarinet-cli --locked && cargo test --package=clarinet-cli + + # - name: Generate coverage + # run: grcov . --binary-path ./target/debug/ -s . -t lcov --branch --ignore-not-existing --ignore "/*" -o lcov.info + + # # Run functional tests here in addition to the other jobs so we can fail fast + # # Since these tests are reached much earlier in the pipeline + # - name: Functional Tests + # if: matrix.name == 'clarinet' + # run: | + # for testdir in $(ls components/clarinet-cli/examples); do + # ./target/debug/clarinet test --manifest-path components/clarinet-cli/examples/${testdir}/Clarinet.toml + # done + + # - name: Upload coverage report + # uses: codecov/codecov-action@v1 + # with: + # flags: unittests + # name: ${{ matrix.name }} + # verbose: true + + dist_clarinet: + name: Build Clarinet Distributions + runs-on: ${{ matrix.os }} + needs: pre_run + # Related upstream issue: + # https://github.com/nagisa/rust_libloading/issues/61#issuecomment-607941377 + # + # env: + # CC: deny_c + + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + platform: linux + target: x86_64-unknown-linux-gnu + architecture: x64 + libc: glibc + - os: windows-latest + platform: windows + target: x86_64-pc-windows-msvc + architecture: x64 + - os: macos-latest + platform: darwin + target: x86_64-apple-darwin + architecture: x64 + - os: macos-latest + platform: darwin + target: aarch64-apple-darwin + architecture: arm64 + + steps: + - name: Configure git to use LF (Windows) + if: matrix.os == 'windows-latest' + run: | + git config --global core.autocrlf false + git config --global core.eol lf + + - name: Checkout repository + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + target: ${{ matrix.target }} + profile: minimal + components: llvm-tools-preview + override: true + + - name: Install wix (Windows) + if: matrix.os == 'windows-latest' + run: cargo install cargo-wix + + - if: matrix.os != 'windows-latest' + run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/ + + - name: Cache cargo + uses: actions/cache@v2 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/${{ matrix.target }}/release/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + # Set environment variables required from cross compiling from macos-x86_64 to macos-arm64 + - name: Configure macos-arm64 cross compile config + if: matrix.target == 'aarch64-apple-darwin' + run: | + echo "SDKROOT=$(xcrun -sdk macosx --show-sdk-path)" >> $GITHUB_ENV + echo "MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx --show-sdk-platform-version)" >> $GITHUB_ENV + + - name: Configure artifact names (libc) + if: ${{ matrix.libc }} + shell: bash + run: | + echo "SHORT_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}-${{ matrix.libc }}" >> $GITHUB_ENV + echo "PRE_GYP_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}-${{ matrix.libc }}" >> $GITHUB_ENV + + - name: Configure artifact names (not libc) + if: ${{ ! matrix.libc }} + shell: bash + run: | + echo "SHORT_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}" >> $GITHUB_ENV + echo "PRE_GYP_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}-unknown" >> $GITHUB_ENV + + - name: Build - Cargo + if: matrix.target != 'x86_64-unknown-linux-musl' + run: cargo build --release --features=telemetry --locked --target ${{ matrix.target }} + + - name: Code sign bin (Windows) + if: startsWith(github.ref, 'refs/heads/main') && matrix.os == 'windows-latest' + run: | + $certificate_file_name = "${env:TEMP}\certificate.pfx" + + $bytes_cert = [Convert]::FromBase64String('${{ secrets.WINDOWS_CODE_SIGNING_CERTIFICATE }}') + [IO.File]::WriteAllBytes(${certificate_file_name}, ${bytes_cert}) + + $signtool_path = ((Resolve-Path -Path "${env:ProgramFiles(x86)}/Windows Kits/10/bin/10*/x86").Path[-1]) + "/signtool.exe" + $bin_path = (Resolve-Path -Path "target/${{ matrix.target }}/release/clarinet.exe").Path + & ${signtool_path} sign ` + /d "Clarinet is a clarity runtime packaged as a command line tool, designed to facilitate smart contract understanding, development, testing and deployment." ` + /du "https://github.com/hirosystems/clarinet" ` + /tr http://timestamp.digicert.com ` + /td sha256 ` + /fd sha256 ` + -f "${certificate_file_name}" ` + -p "${{ secrets.WINDOWS_CODE_SIGNING_PASSWORD }}" ` + "${bin_path}" + + - name: Build Installer (Windows) + if: matrix.os == 'windows-latest' + run: cargo wix -v --no-build --nocapture -p clarinet-cli + + - name: Code sign installer (Windows) + if: startsWith(github.ref, 'refs/heads/main') && matrix.os == 'windows-latest' + run: | + $certificate_file_name = "${env:TEMP}\certificate.pfx" + + $bytes_cert = [Convert]::FromBase64String('${{ secrets.WINDOWS_CODE_SIGNING_CERTIFICATE }}') + [IO.File]::WriteAllBytes(${certificate_file_name}, ${bytes_cert}) + + $signtool_path = ((Resolve-Path -Path "${env:ProgramFiles(x86)}/Windows Kits/10/bin/10*/x86").Path[-1]) + "/signtool.exe" + $msi_path = (Resolve-Path -Path "target/wix/*.msi").Path + & ${signtool_path} sign ` + /d "Clarinet is a clarity runtime packaged as a command line tool, designed to facilitate smart contract understanding, development, testing and deployment." ` + /du "https://github.com/hirosystems/clarinet" ` + /tr http://timestamp.digicert.com ` + /td sha256 ` + /fd sha256 ` + -f "${certificate_file_name}" ` + -p "${{ secrets.WINDOWS_CODE_SIGNING_PASSWORD }}" ` + "${msi_path}" + + # Don't compress for Windows because winget can't yet unzip files + - name: Compress cargo artifact (Linux) + if: matrix.os != 'windows-latest' + run: tar -C target/${{ matrix.target }}/release -zcvf clarinet-${{ env.SHORT_TARGET_NAME }}.tar.gz clarinet + + - name: Rename cargo artifact (Windows) + if: matrix.os == 'windows-latest' + shell: bash + run: mv target/wix/*.msi clarinet-${{ env.SHORT_TARGET_NAME }}.msi + + # Separate uploads to prevent paths from being preserved + - name: Upload cargo artifacts (Linux) + if: matrix.os != 'windows-latest' + uses: actions/upload-artifact@v2 + with: + name: clarinet-${{ env.SHORT_TARGET_NAME }} + path: clarinet-${{ env.SHORT_TARGET_NAME }}.tar.gz + + - name: Upload cargo artifact (Windows) + if: matrix.os == 'windows-latest' + uses: actions/upload-artifact@v2 + with: + name: clarinet-${{ env.SHORT_TARGET_NAME }} + path: clarinet-${{ env.SHORT_TARGET_NAME }}.msi + + - name: Unit Tests - Cargo + # can't easily run mac-arm64 tests in GH without native runners for that arch + if: matrix.target != 'aarch64-apple-darwin' + run: cargo test --release --locked --target ${{ matrix.target }} + + - name: Functional Tests (Linux) + # can't easily run mac-arm64 tests in GH without native runners for that arch + if: matrix.os != 'windows-latest' && matrix.target != 'aarch64-apple-darwin' + run: | + for testdir in $(ls components/clarinet-cli/examples); do + ./target/${{ matrix.target }}/release/clarinet test --manifest-path components/clarinet-cli/examples/${testdir}/Clarinet.toml + done + + - name: Functional Tests (Windows) + if: matrix.os == 'windows-latest' + run: | + foreach($testdir in Get-ChildItem components/clarinet-cli/examples) { + ./target/${{ matrix.target }}/release/clarinet test --manifest-path ${testdir}/Clarinet.toml + } + + dist_stacks_devnet_js: + name: Build Stacks Devnet JS Distributions + runs-on: ${{ matrix.os }} + needs: + - pre_run + - get_release_info + + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + platform: linux + target: x86_64-unknown-linux-gnu + architecture: x64 + libc: glibc + - os: windows-latest + platform: windows + target: x86_64-pc-windows-msvc + architecture: x64 + - os: macos-latest + platform: darwin + target: x86_64-apple-darwin + architecture: x64 + - os: macos-latest + platform: darwin + target: aarch64-apple-darwin + architecture: arm64 + - os: ubuntu-latest + platform: linux + target: x86_64-unknown-linux-musl + architecture: x64 + libc: musl + + steps: + - name: Configure git to use LF (Windows) + if: matrix.os == 'windows-latest' && github.event_name != 'pull_request' + run: | + git config --global core.autocrlf false + git config --global core.eol lf + + - name: Checkout repository + if: github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu' + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Install Rust toolchain + if: github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu' + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + target: ${{ matrix.target }} + profile: minimal + components: llvm-tools-preview + override: true + + - name: Install and cache Node + if: github.event_name != 'pull_request' && matrix.target != 'x86_64-unknown-linux-musl' + uses: actions/setup-node@v3 + with: + node-version: "14" + # Host nodejs arch does not matter in our usecase for compiling cross-platform npm packages, + # if enabled, this will fail after installing an arm64 nodejs runtime for an x86_64 arch macos system + # architecture: ${{ matrix.architecture }} + cache: npm + cache-dependency-path: components/stacks-devnet-js/package-lock.json + + - name: Cache cargo + if: github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu' + uses: actions/cache@v2 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/${{ matrix.target }}/release/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + # Set environment variables required from cross compiling from macos-x86_64 to macos-arm64 + - name: Configure macos-arm64 cross compile config + if: github.event_name != 'pull_request' && matrix.target == 'aarch64-apple-darwin' + run: | + echo "SDKROOT=$(xcrun -sdk macosx --show-sdk-path)" >> $GITHUB_ENV + echo "MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx --show-sdk-platform-version)" >> $GITHUB_ENV + + - name: Configure artifact names (libc) + if: (github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu') && matrix.libc + shell: bash + run: | + echo "SHORT_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}-${{ matrix.libc }}" >> $GITHUB_ENV + echo "PRE_GYP_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}-${{ matrix.libc }}" >> $GITHUB_ENV + + - name: Configure artifact names (not libc) + if: github.event_name != 'pull_request' && ! matrix.libc + shell: bash + run: | + echo "SHORT_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}" >> $GITHUB_ENV + echo "PRE_GYP_TARGET_NAME=${{ matrix.platform }}-${{ matrix.architecture }}-unknown" >> $GITHUB_ENV + + - name: Build - Node + if: (github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu') && matrix.target != 'x86_64-unknown-linux-musl' + working-directory: components/stacks-devnet-js + run: | + npm install --ignore-scripts + npm run build-${{ env.SHORT_TARGET_NAME }} + + - name: Build - Node (linux-musl) + if: github.event_name != 'pull_request' && matrix.target == 'x86_64-unknown-linux-musl' + uses: docker://rust:alpine3.15 + env: + RUSTFLAGS: -C target-feature=-crt-static + with: + entrypoint: /bin/sh + args: -c " + cd components/stacks-devnet-js && + apk add alpine-sdk nodejs npm git && + npm install --ignore-scripts && + npm run build-${{ env.SHORT_TARGET_NAME }}" + + - name: Compress node artifact + if: github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu' + shell: bash + run: tar -C components/stacks-devnet-js -zcvf stacks-devnet-js-${{ env.PRE_GYP_TARGET_NAME }}.tar.gz native/index.node + + - name: Upload node artifact + if: github.event_name != 'pull_request' || matrix.target == 'x86_64-unknown-linux-gnu' + uses: actions/upload-artifact@v2 + with: + name: stacks-devnet-js-${{ env.PRE_GYP_TARGET_NAME }} + path: stacks-devnet-js-${{ env.PRE_GYP_TARGET_NAME }}.tar.gz + + # - name: Unit Tests - Node + # working-directory: node-bindings + # run: npm run spec + + - name: NPM Publish + uses: JS-DevTools/npm-publish@v1 + if: matrix.target == 'x86_64-unknown-linux-gnu' && startsWith(github.ref, 'refs/heads/main') && needs.get_release_info.outputs.tag != '' + with: + package: components/stacks-devnet-js/package.json + access: public + greater-version-only: true + token: ${{ secrets.NPM_TOKEN }} + + dist_chainhook_node: + name: Build Chainhook node Distribution + runs-on: ubuntu-latest + needs: pre_run + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + target: x86_64-unknown-linux-gnu + profile: minimal + components: llvm-tools-preview + override: true + + - name: Cache cargo + uses: actions/cache@v2 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/x86_64-unknown-linux-gnu/release/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + - name: Configure artifact names + shell: bash + run: | + echo "SHORT_TARGET_NAME=linux-x64-glibc" >> $GITHUB_ENV + echo "PRE_GYP_TARGET_NAME=linux-x64-glibc" >> $GITHUB_ENV + + - name: Build - Cargo + working-directory: components/chainhook-cli + run: cargo build --release --locked --target x86_64-unknown-linux-gnu + + - name: Compress cargo artifact + run: tar -C target/x86_64-unknown-linux-gnu/release -zcvf chainhook-cli-${{ env.SHORT_TARGET_NAME }}.tar.gz chainhook-cli + + - name: Upload cargo artifacts + uses: actions/upload-artifact@v2 + with: + name: chainhook-cli-${{ env.SHORT_TARGET_NAME }} + path: chainhook-cli-${{ env.SHORT_TARGET_NAME }}.tar.gz + + - name: Unit Tests - Cargo + run: cargo test --release --locked --target x86_64-unknown-linux-gnu + + dist_clarity_repl: + name: Build Clarity REPL Distribution + runs-on: ubuntu-latest + needs: pre_run + defaults: + run: + working-directory: components/clarity-repl + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Install Rust toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + target: x86_64-unknown-linux-gnu + profile: minimal + components: llvm-tools-preview + override: true + + - name: Cache cargo + uses: actions/cache@v2 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/x86_64-unknown-linux-gnu/release/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + + - name: Configure artifact names + run: | + echo "SHORT_TARGET_NAME=linux-x64-glibc" >> $GITHUB_ENV + echo "PRE_GYP_TARGET_NAME=linux-x64-glibc" >> $GITHUB_ENV + + - name: Install dependencies + run: cargo install --force wasm-pack + + - name: Build - Cargo + run: cargo build --release --locked --target x86_64-unknown-linux-gnu + + # - name: Build - WASM + # run: wasm-pack build --target web --release -- --no-default-features --features wasm + + - name: Compress cargo artifact + working-directory: "." + run: tar -C target/x86_64-unknown-linux-gnu/release -zcvf clarity-repl-${{ env.SHORT_TARGET_NAME }}.tar.gz clarity-repl + + # - name: Compress wasm artifact + # working-directory: "." + # run: tar -C target/wasm32-unknown-unknown/release -zcvf clarity-repl-wasm.tar.gz clarity_repl.wasm + + - name: Upload cargo artifact + uses: actions/upload-artifact@v2 + with: + name: clarity-repl-${{ env.SHORT_TARGET_NAME }} + path: clarity-repl-${{ env.SHORT_TARGET_NAME }}.tar.gz + + # - name: Upload wasm artifact + # uses: actions/upload-artifact@v2 + # with: + # name: clarity-repl-wasm + # path: clarity-repl-wasm.tar.gz + + - name: Unit Tests - Cargo + run: cargo test --release --locked --target x86_64-unknown-linux-gnu + + - name: Publish clarity-repl to crates.io + if: startsWith(github.ref, 'refs/heads/main') && needs.get_release_info.outputs.tag != '' + run: | + cargo login ${{ secrets.CARGO_CRATES_IO_API_KEY }} + cargo publish + + docker_images: + name: Create ${{ matrix.name }} Docker Image + runs-on: ubuntu-latest + needs: + - get_release_info + - dist_clarinet + - dist_chainhook_node + outputs: + version: ${{ steps.docker_meta.outputs.version }} + strategy: + fail-fast: false + matrix: + include: + - name: Clarinet + description: Clarinet is a simple, modern and opinionated runtime for testing, integrating and deploying Clarity smart contracts. + image: ${{ github.repository }} + artifact: clarinet-linux-x64-glibc + dockerfile: dockerfiles/components/clarinet.dockerfile + - name: Chainhook Node + description: A Stacks event observer. + image: ${{ github.repository_owner }}/chainhook-cli + artifact: chainhook-cli-linux-x64-glibc + dockerfile: dockerfiles/components/chainhook-cli.dockerfile + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Generate Docker tags/labels + id: docker_meta + uses: docker/metadata-action@v4 + with: + images: ${{ matrix.image }} + tags: | + type=ref,event=branch + type=ref,event=pr + type=semver,pattern={{version}},value=${{ needs.get_release_info.outputs.tag }},enable=${{ needs.get_release_info.outputs.tag != '' }} + type=semver,pattern={{major}}.{{minor}},value=${{ needs.get_release_info.outputs.tag }},enable=${{ needs.get_release_info.outputs.tag != '' }} + labels: | + org.opencontainers.image.title=${{ matrix.name }} + org.opencontainers.image.description=${{ matrix.description }} + + - name: Login to Dockerhub + uses: docker/login-action@v2 + if: github.event_name != 'pull_request' + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Download pre-built dist + uses: actions/download-artifact@v3 + with: + name: ${{ matrix.artifact }} + + - name: Untar pre-built dist + run: tar zxvf *.tar.gz + + - name: Create Image + uses: docker/build-push-action@v3 + with: + context: . + file: ${{ matrix.dockerfile }} + push: ${{ github.event_name != 'pull_request' }} + tags: ${{ steps.docker_meta.outputs.tags }} + labels: ${{ steps.docker_meta.outputs.labels }} + + release: + name: Release + runs-on: ubuntu-latest + if: startsWith(github.ref, 'refs/heads/main') && needs.get_release_info.outputs.tag != '' + needs: + - get_release_info + - audit + # - test_coverage_cargo + - dist_stacks_devnet_js + - dist_clarity_repl + - docker_images + permissions: + actions: write + contents: write + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Download pre-built dists + uses: actions/download-artifact@v3 + + - name: Tag and Release + uses: ncipollo/release-action@v1 + with: + artifacts: "**/*.tar.gz,**/*.msi" + tag: ${{ needs.get_release_info.outputs.tag }} + commit: ${{ env.GITHUB_SHA }} + + - name: Trigger pkg-version-bump workflow + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + event-type: released + client-payload: '{"tag": "${{ needs.get_release_info.outputs.tag }}"}' diff --git a/.github/workflows/new-issues.yaml b/.github/workflows/new-issues.yaml new file mode 100644 index 0000000..a24aa26 --- /dev/null +++ b/.github/workflows/new-issues.yaml @@ -0,0 +1,16 @@ +name: Add issues to Clarinet project + +on: + issues: + types: + - opened + +jobs: + add-to-project: + name: Add issue to project Clarinet + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@main + with: + project-url: https://github.com/orgs/hirosystems/projects/15 + github-token: ${{ secrets.GH_TOKEN }} diff --git a/.github/workflows/pkg-version-bump.yaml b/.github/workflows/pkg-version-bump.yaml new file mode 100644 index 0000000..a119926 --- /dev/null +++ b/.github/workflows/pkg-version-bump.yaml @@ -0,0 +1,64 @@ +## +## Bumps the Clarinet version listed on various package managers. +## + +name: Package Version Bump +on: + workflow_dispatch: + inputs: + tag: + description: 'The tag of the release.' + required: true + repository_dispatch: + types: + - released + +env: + GIT_USER_NAME: Hiro DevOps + GIT_USER_EMAIL: 45208873+blockstack-devops@users.noreply.github.com + +jobs: + homebrew: + name: Homebrew + runs-on: macos-latest + steps: + - name: Homebrew version bump + env: + HOMEBREW_GITHUB_API_TOKEN: ${{ secrets.GH_TOKEN }} + TAG: ${{ github.event.client_payload.tag || github.event.inputs.tag }} + run: | + git config --global user.name "${GIT_USER_NAME}" + git config --global user.email "${GIT_USER_EMAIL}" + + brew update + brew bump-formula-pr \ + --no-browse \ + --no-audit \ + --tag "${TAG}" \ + ${{ github.event.repository.name }} + + winget: + name: Winget + runs-on: windows-latest + steps: + - name: Winget version bump + env: + TAG: ${{ github.event.client_payload.tag || github.event.inputs.tag }} + run: | + # Get version infoq + $VERSION=${env:TAG}.substring(1) + + # Configure git configs + git config --global user.name "${env:GIT_USER_NAME}" + git config --global user.email "${env:GIT_USER_EMAIL}" + + # Get wingetcreate + iwr https://aka.ms/wingetcreate/latest -OutFile wingetcreate.exe + + # Update manifest and submit PR + ./wingetcreate.exe update ` + --urls https://github.com/${{ github.repository }}/releases/download/${env:TAG}/clarinet-windows-x64.msi ` + --version ${VERSION} ` + --token ${{ secrets.GH_TOKEN }} ` + --submit ` + HiroSystems.Clarinet diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..53ee18c --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +/target +.DS_Store +clarinet.code-workspace +history.txt +node_modules +**/node_modules +target +index.node +npm-debug.log* +**/settings/Mainnet.toml +**/settings/Testnet.toml +**/.requirements +**/.cache +**/.build +components/stacks-devnet-js/dist +components/stacks-devnet-js/build +components/chainhook-types-js/dist +*.tar.gz +*.zip +*.rdb + +components/chainhook-db/examples/arkadiko-data-indexing/vault-monitor/bin +components/chainhook-db/examples/arkadiko-data-indexing/vault-monitor/tmp +components/chainhook-db/examples/arkadiko-data-indexing/vault-monitor/vendor +components/chainhook-cli/cache diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3b3fd86 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,30 @@ +#### 1.4.0 (2023-01-23) + +##### New Features + +* Polish LSP completion capability ([4cc24ed3](https://github.com/hirosystems/clarinet/commit/4cc24ed3c5edaf61d057c4c1e1ab3d32957e6a15), [16db8dd4](https://github.com/hirosystems/clarinet/commit/16db8dd454ddc5acaec1161ef4aba26cba4c37bf), [905e5433](https://github.com/hirosystems/clarinet/commit/905e5433cc7bf208ea480cc148865e8198bb0420), [9ffdad0f](https://github.com/hirosystems/clarinet/commit/9ffdad0f46294dd36c83ab92c3241b2b01499576), [d3a27933](https://github.com/hirosystems/clarinet/commit/d3a2793350e96ad224f038b11a6ada602fef46af), [cad54358](https://github.com/hirosystems/clarinet/commit/cad54358a1978ab4953aca9e0f3a6ff52ac3afc4), [439c4933](https://github.com/hirosystems/clarinet/commit/439c4933bcbeaaec9f3413892bbcc12fc8ec1b15)) +* Upgrade clarity vm ([fefdd1e0](https://github.com/hirosystems/clarinet/commit/fefdd1e092dad8e546e2db7683202d81dd91407a)) +* Upgrade stacks-node next image ([492804bb](https://github.com/hirosystems/clarinet/commit/492804bb472a950dded1b1d0c8a951b434a141ac)) +* Expose stacks-node settings wait_time_for_microblocks, first_attempt_time_ms, subsequent_attempt_time_ms in Devnet config file +* Improve Epoch 2.1 deployments handling +* Improve `stacks-devnet-js` stability + +##### Documentation + +* Updated documentation to set clarity version of contract ([b124d96f](https://github.com/hirosystems/clarinet/commit/b124d96fbbef29befc26601cdbd8ed521d4a162a)) + + +# [1.3.1](https://github.com/hirosystems/clarinet/compare/v1.3.0...v1.3.1) (2023-01-03) + +### New Features + +* Introduce use_docker_gateway_routing setting for CI environments +* Improve signature help in LSP ([eee03cff](https://github.com/hirosystems/clarinet/commit/eee03cff757d3e288abe7436eca06d4c440c71dc)) +* Add support for more keyword help in REPL ([f564d469](https://github.com/hirosystems/clarinet/commit/f564d469ccf5e79ab924643627fdda8715da6a1d, [0efcc75e](https://github.com/hirosystems/clarinet/commit/0efcc75e7da3b801e1a862094791f3747452f9e0)) +* Various Docker management optimizations / fixes ([b379d29f](https://github.com/hirosystems/clarinet/commit/b379d29f4ad4e85df42e804bc00cec2baff375c0), [4f4c8806](https://github.com/hirosystems/clarinet/commit/4f4c88064e2045de9e48d75b507dd321d4543046)) + +### Bug Fixes + +* Fix STX assets title ([fdc748e7](https://github.com/hirosystems/clarinet/commit/fdc748e7b7df6ef1a6b62ab5cb8c1b68bde9b1ad), [ce5d107c](https://github.com/hirosystems/clarinet/commit/ce5d107c76950d989eb0be8283adf35930283f18)) +* Fix define function grammar ([d02835ba](https://github.com/hirosystems/clarinet/commit/d02835bab06578eebb13a791f9faa1c2571d3fb9)) +* Fix get_costs panicking ([822d8e29](https://github.com/hirosystems/clarinet/commit/822d8e29965e11864f708a1efd7a8ad385bc1ba3), [e41ae715](https://github.com/hirosystems/clarinet/commit/e41ae71585a432d21cc16c109d2858f9e1d8e22b)) diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..feb1135 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,8079 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "Inflector" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" +dependencies = [ + "lazy_static", + "regex", +] + +[[package]] +name = "addr2line" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ecd88a8c8378ca913a680cd98f0f13ac67383d35993f86c90a70e3f137816b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aead" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b613b8e1e3cf911a086f53f03bf286f52fd7a7258e4fa606f0ef220d39d8877" +dependencies = [ + "generic-array 0.14.6", +] + +[[package]] +name = "aes" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e8b47f52ea9bae42228d07ec09eb676433d7c4ed1ebdf0f1d1c29ed446f1ab8" +dependencies = [ + "cfg-if", + "cipher 0.3.0", + "cpufeatures", + "opaque-debug 0.3.0", +] + +[[package]] +name = "aes" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241" +dependencies = [ + "cfg-if", + "cipher 0.4.3", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df5f85a83a7d8b0442b6aa7b504b8212c1733da07b98aae43d4bc21b2cb3cdf6" +dependencies = [ + "aead", + "aes 0.7.5", + "cipher 0.3.0", + "ctr 0.8.0", + "ghash", + "subtle 2.4.1", +] + +[[package]] +name = "aes-gcm" +version = "0.10.0-pre" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8004e8b23ff2c65e28ff77bab0eccd36f4a6c2c8e0b55c46acba481425cc3a4f" +dependencies = [ + "aead", + "aes 0.8.2", + "cipher 0.4.3", + "ctr 0.9.2", + "ghash", + "subtle 2.4.1", +] + +[[package]] +name = "aes-kw" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69fa2b352dcefb5f7f3a5fb840e02665d311d878955380515e4fd50095dd3d8c" +dependencies = [ + "aes 0.8.2", +] + +[[package]] +name = "ahash" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +dependencies = [ + "getrandom 0.2.8", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "ansi_term" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" +dependencies = [ + "winapi", +] + +[[package]] +name = "anyhow" +version = "1.0.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6" + +[[package]] +name = "anymap" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33954243bd79057c2de7338850b85983a44588021f8a5fee574a8888c6de4344" + +[[package]] +name = "arc-swap" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "983cd8b9d4b02a6dc6ffa557262eb5858a27a0038ffffe21a0f133eaa819a164" + +[[package]] +name = "arrayref" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" + +[[package]] +name = "arrayvec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" + +[[package]] +name = "ast_node" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf94863c5fdfee166d0907c44e5fee970123b2b7307046d35d1e671aa93afbba" +dependencies = [ + "darling", + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "async-compression" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "942c7cd7ae39e91bde4820d74132e9862e62c2f386c3aa90ccf55949f5bad63a" +dependencies = [ + "brotli", + "flate2", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-stream" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad5c83079eae9969be7fadefe640a1c566901f05ff91ab221de4b6f68d9507e" +dependencies = [ + "async-stream-impl", + "futures-core", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10f203db73a71dfa2fb6dd22763990fa26f3d2625a6da2da900d23b87d26be27" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "async-trait" +version = "0.1.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31e6e93155431f3931513b243d371981bb2770112b370c82745a1d19d2f99364" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "atomic" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b88d82667eca772c4aa12f0f1348b3ae643424c8876448f3f7bd5787032e234c" +dependencies = [ + "autocfg 1.1.0", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "auto_impl" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7862e21c893d65a1650125d157eaeec691439379a1cee17ee49031b79236ada4" +dependencies = [ + "proc-macro-error", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "autocfg" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde43e75fd43e8a1bf86103336bc699aa8d17ad1be60c76c0bdfd4828e19b78" +dependencies = [ + "autocfg 1.1.0", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "backtrace" +version = "0.3.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab84319d616cfb654d03394f38ab7e6f0919e181b1b57e1fd15e7fb4077d9a7" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide 0.5.4", + "object", + "rustc-demangle", +] + +[[package]] +name = "base-x" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" + +[[package]] +name = "base16ct" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" + +[[package]] +name = "base58" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5024ee8015f02155eee35c711107ddd9a9bf3cb689cf2a9089c97e79b6e1ae83" + +[[package]] +name = "base58" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6107fe1be6682a68940da878d9e9f5e90ca5745b3dec9fd1bb393c8777d4f581" + +[[package]] +name = "base64" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b41b7ea54a0c9d92199de89e20e58d49f02f8e699814ef3fdf266f6f748d15c7" + +[[package]] +name = "base64" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff" + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64-compat" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a8d4d2746f89841e49230dd26917df1876050f95abafafbe34f47cb534b88d7" +dependencies = [ + "byteorder", +] + +[[package]] +name = "base64-simd" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278c7ba87265587c4823cf1b2fdf57834151540b2e509574adb03627f8c7f22d" +dependencies = [ + "simd-abstraction", +] + +[[package]] +name = "base64ct" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b645a089122eccb6111b4f81cbc1a49f5900ac4666bb93ac027feaecf15607bf" + +[[package]] +name = "bech32" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d86b93f97252c47b41663388e6d155714a9d0c398b99f1005cbc5f978b29f445" + +[[package]] +name = "better_scoped_tls" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73e8ecdec39e98aa3b19e8cd0b8ed8f77ccb86a6b0b2dc7cd86d105438a2123" +dependencies = [ + "scoped-tls", +] + +[[package]] +name = "binascii" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" + +[[package]] +name = "bip39" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e89470017230c38e52b82b3ee3f530db1856ba1d434e3a67a3456a8a8dec5f" +dependencies = [ + "bitcoin_hashes 0.9.7", + "rand_core 0.4.2", +] + +[[package]] +name = "bitcoin" +version = "0.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0694ea59225b0c5f3cb405ff3f670e4828358ed26aec49dc352f730f0cb1a8a3" +dependencies = [ + "bech32", + "bitcoin_hashes 0.11.0", + "secp256k1", + "serde", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce18265ec2324ad075345d5814fbeed4f41f0a660055dc78840b74d19b874b1" + +[[package]] +name = "bitcoin_hashes" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90064b8dee6815a6470d60bad07bbbaee885c0e12d04177138fa3291a01b7bc4" +dependencies = [ + "serde", +] + +[[package]] +name = "bitcoincore-rpc" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0261b2bb7617e0c91b452a837bbd1291fd34ad6990cb8e3ffc28239cc045b5ca" +dependencies = [ + "bitcoincore-rpc-json", + "jsonrpc", + "log", + "serde", + "serde_json", +] + +[[package]] +name = "bitcoincore-rpc-json" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c231bea28e314879c5aef240f6052e8a72a369e3c9f9b20d9bfbb33ad18029b2" +dependencies = [ + "bitcoin", + "serde", + "serde_json", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "blake2b_simd" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" +dependencies = [ + "arrayref", + "arrayvec", + "constant_time_eq", +] + +[[package]] +name = "block-buffer" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" +dependencies = [ + "block-padding 0.1.5", + "byte-tools", + "byteorder", + "generic-array 0.12.4", +] + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "block-padding 0.2.1", + "generic-array 0.14.6", +] + +[[package]] +name = "block-buffer" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e" +dependencies = [ + "generic-array 0.14.6", +] + +[[package]] +name = "block-modes" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb03d1bed155d89dce0f845b7899b18a9a163e148fd004e1c28421a783e2d8e" +dependencies = [ + "block-padding 0.2.1", + "cipher 0.3.0", +] + +[[package]] +name = "block-modes" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e2211b0817f061502a8dd9f11a37e879e79763e3c698d2418cf824d8cb2f21e" + +[[package]] +name = "block-padding" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" +dependencies = [ + "byte-tools", +] + +[[package]] +name = "block-padding" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" + +[[package]] +name = "block-padding" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a90ec2df9600c28a01c56c4784c9207a96d2451833aeceb8cc97e4c9548bb78" +dependencies = [ + "generic-array 0.14.6", +] + +[[package]] +name = "bollard" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92fed694fd5a7468c971538351c61b9c115f1ae6ed411cd2800f0f299403a4b" +dependencies = [ + "base64 0.13.1", + "bollard-stubs", + "bytes", + "chrono", + "dirs-next", + "futures-core", + "futures-util", + "hex 0.4.3", + "http", + "hyper", + "hyperlocal", + "log", + "pin-project", + "serde", + "serde_derive", + "serde_json", + "serde_urlencoded", + "thiserror", + "tokio", + "tokio-util 0.6.10", + "url", + "winapi", +] + +[[package]] +name = "bollard-stubs" +version = "1.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2f2e73fffe9455141e170fb9c1feb0ac521ec7e7dcd47a7cab72a658490fb8" +dependencies = [ + "chrono", + "serde", + "serde_with", +] + +[[package]] +name = "brotli" +version = "3.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ad2d4653bf5ca36ae797b1f4bb4dbddb60ce49ca4aed8a2ce4829f60425b80" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bstr" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +dependencies = [ + "lazy_static", + "memchr", + "regex-automata", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" + +[[package]] +name = "byte-tools" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "bytes" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c" + +[[package]] +name = "cache_control" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf2a5fb3207c12b5d208ebc145f967fea5cac41a021c37417ccc31ba40f39ee" + +[[package]] +name = "cassowary" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.3", +] + +[[package]] +name = "cc" +version = "1.0.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" +dependencies = [ + "jobserver", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chainhook-cli" +version = "0.1.0" +dependencies = [ + "ansi_term", + "atty", + "bitcoincore-rpc", + "bitcoincore-rpc-json", + "chainhook-event-observer", + "chainhook-types", + "clap 3.2.23", + "clap_generate", + "clarity-repl", + "criterion", + "crossbeam-channel", + "csv", + "ctrlc", + "flate2", + "flume", + "futures-util", + "hex 0.4.3", + "hiro-system-kit", + "num_cpus", + "redis", + "reqwest", + "serde", + "serde-redis", + "serde_derive", + "serde_json", + "tar", + "tokio", + "toml 0.5.9", +] + +[[package]] +name = "chainhook-event-observer" +version = "1.0.0" +dependencies = [ + "base58 0.2.0", + "base64 0.13.1", + "bitcoincore-rpc", + "bitcoincore-rpc-json", + "chainhook-types", + "clap 3.2.23", + "clap_generate", + "clarinet-utils", + "clarity-repl", + "crossbeam-channel", + "ctrlc", + "hiro-system-kit", + "reqwest", + "rocket", + "rocket_okapi", + "schemars", + "serde", + "serde_derive", + "serde_json", + "stacks-rpc-client", + "tokio", + "toml 0.5.9", +] + +[[package]] +name = "chainhook-types" +version = "1.0.0" +dependencies = [ + "schemars", + "serde", + "serde_derive", + "serde_json", + "strum", +] + +[[package]] +name = "chrono" +version = "0.4.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-integer", + "num-traits", + "serde", + "time 0.1.45", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "cipher" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" +dependencies = [ + "generic-array 0.14.6", +] + +[[package]] +name = "cipher" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1873270f8f7942c191139cb8a40fd228da6c3fd2fc376d7e92d47aa14aeb59e" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "2.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +dependencies = [ + "bitflags", + "textwrap 0.11.0", + "unicode-width", +] + +[[package]] +name = "clap" +version = "3.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5" +dependencies = [ + "atty", + "bitflags", + "clap_derive", + "clap_lex", + "indexmap", + "once_cell", + "strsim", + "termcolor", + "textwrap 0.16.0", +] + +[[package]] +name = "clap_complete" +version = "3.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f7a2e0a962c45ce25afce14220bc24f9dade0a1787f185cecf96bfba7847cd8" +dependencies = [ + "clap 3.2.23", +] + +[[package]] +name = "clap_derive" +version = "3.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65" +dependencies = [ + "heck 0.4.0", + "proc-macro-error", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "clap_generate" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1b28c4a802ac3628604fd267cac62aaea74dc61af3410db6b1c44c03b42599" +dependencies = [ + "clap 3.2.23", + "clap_complete", +] + +[[package]] +name = "clap_lex" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "clarinet-cli" +version = "1.4.0" +dependencies = [ + "aes 0.7.5", + "ansi_term", + "atty", + "base58 0.2.0", + "base64 0.13.1", + "bitcoin", + "block-modes 0.8.1", + "cache_control", + "chainhook-event-observer", + "chainhook-types", + "chrono", + "clap 3.2.23", + "clap_generate", + "clarinet-deployments", + "clarinet-files", + "clarinet-utils", + "clarity-lsp", + "clarity-repl", + "crossbeam-channel", + "crossterm 0.22.1", + "ctrlc", + "data-url", + "deno_ast", + "deno_broadcast_channel", + "deno_console", + "deno_core", + "deno_crypto", + "deno_emit", + "deno_fetch", + "deno_graph", + "deno_http", + "deno_net", + "deno_ops", + "deno_tls", + "deno_url", + "deno_web", + "deno_webidl", + "deno_websocket", + "deno_webstorage", + "dlopen", + "dprint-plugin-json", + "dprint-plugin-markdown", + "dprint-plugin-typescript", + "encoding_rs", + "env_logger", + "filetime", + "fs3", + "futures", + "fwdansi", + "hex 0.4.3", + "hiro-system-kit", + "hmac 0.12.1", + "http", + "hyper", + "import_map", + "indexmap", + "jsonc-parser", + "lazy_static", + "libc", + "libsecp256k1 0.7.1", + "log", + "lzzzz", + "mac_address", + "mio 0.8.5", + "mitata", + "netif", + "nix 0.24.2", + "node_resolver", + "notify", + "num_cpus", + "once_cell", + "os_pipe", + "pbkdf2", + "percent-encoding", + "pin-project", + "rand 0.8.5", + "regex", + "reqwest", + "ring", + "rsa", + "segment", + "semver-parser 0.10.2", + "serde", + "serde_derive", + "serde_json", + "serde_yaml", + "sha2 0.10.6", + "shell-escape", + "signal-hook-registry", + "similar", + "stacks-network", + "strum", + "sys-info", + "tempfile", + "termcolor", + "text-size", + "text_lines 0.6.0", + "tokio", + "tokio-util 0.7.2", + "toml 0.5.9", + "tower-lsp", + "tui", + "twox-hash", + "typed-arena", + "uuid 1.0.0", + "walkdir", + "winapi", + "winres", + "zstd", +] + +[[package]] +name = "clarinet-deployments" +version = "1.0.0" +dependencies = [ + "base58 0.2.0", + "bitcoin", + "bitcoincore-rpc", + "bitcoincore-rpc-json", + "chainhook-types", + "clarinet-files", + "clarinet-utils", + "clarity-repl", + "libsecp256k1 0.7.1", + "reqwest", + "serde", + "serde_derive", + "serde_json", + "serde_yaml", + "stacks-rpc-client", + "tiny-hderive", +] + +[[package]] +name = "clarinet-files" +version = "1.0.0" +dependencies = [ + "bip39", + "bitcoin", + "chainhook-types", + "clarinet-utils", + "clarity-repl", + "js-sys", + "libsecp256k1 0.7.1", + "serde", + "serde-wasm-bindgen", + "serde_derive", + "tiny-hderive", + "toml 0.5.9", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", +] + +[[package]] +name = "clarinet-utils" +version = "1.0.0" +dependencies = [ + "hmac 0.12.1", + "pbkdf2", + "serde", + "sha2 0.10.6", +] + +[[package]] +name = "clarity" +version = "2.0.0" +source = "git+https://github.com/stacks-network/stacks-blockchain.git?rev=eedba787a36d68213501337ba50d1856f41b869a#eedba787a36d68213501337ba50d1856f41b869a" +dependencies = [ + "integer-sqrt", + "lazy_static", + "rand 0.7.3", + "rand_chacha 0.2.2", + "regex", + "rstest", + "rstest_reuse", + "rusqlite", + "serde", + "serde_derive", + "serde_json", + "serde_stacker", + "sha2-asm", + "stacks-common", + "time 0.2.27", +] + +[[package]] +name = "clarity-jupyter-kernel" +version = "1.0.0" +dependencies = [ + "chrono", + "clarity-repl", + "colored", + "dirs 4.0.0", + "failure", + "hex 0.3.2", + "hmac 0.7.1", + "json", + "lazy_static", + "regex", + "ripemd160 0.8.0", + "sha2 0.8.2", + "sha3 0.8.2", + "uuid 0.7.4", + "zmq", +] + +[[package]] +name = "clarity-lsp" +version = "1.0.0" +dependencies = [ + "chainhook-types", + "clarinet-deployments", + "clarinet-files", + "clarity-repl", + "console_error_panic_hook", + "js-sys", + "lazy_static", + "lsp-types", + "regex", + "serde", + "serde-wasm-bindgen", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "clarity-repl" +version = "1.4.0" +dependencies = [ + "ansi_term", + "atty", + "bytes", + "clarity", + "debug_types", + "futures", + "getrandom 0.2.8", + "hiro-system-kit", + "httparse", + "integer-sqrt", + "lazy_static", + "libsecp256k1 0.5.0", + "log", + "memchr", + "pico-args", + "prettytable-rs", + "rand 0.7.3", + "rand_pcg 0.3.1", + "rand_seeder", + "regex", + "reqwest", + "ripemd160 0.9.1", + "rustyline", + "serde", + "serde_derive", + "serde_json", + "sha2 0.10.6", + "sha3 0.9.1", + "tokio", + "tokio-util 0.7.2", + "wasm-bindgen", + "wasm-bindgen-futures", +] + +[[package]] +name = "clear_on_drop" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38508a63f4979f0048febc9966fadbd48e5dab31fd0ec6a3f151bbf4a74f7423" +dependencies = [ + "cc", +] + +[[package]] +name = "clipboard-win" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ab1b92798304eedc095b53942963240037c0516452cb11aeba709d420b2219" +dependencies = [ + "error-code", + "str-buf", + "winapi", +] + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +dependencies = [ + "bitflags", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + +[[package]] +name = "colored" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ffc801dacf156c5854b9df4f425a626539c3a6ef7893cc0c5084a23f0b6c59" +dependencies = [ + "atty", + "lazy_static", + "winapi", +] + +[[package]] +name = "combine" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35ed6e9d84f0b51a7f52daf1c7d71dd136fd7a3f41a8462b8cdb8c78d920fad4" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "const-oid" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cec318a675afcb6a1ea1d4340e2d377e56e47c266f28043ceccbf4412ddfdd3b" + +[[package]] +name = "const_fn" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbdcdcb6d86f71c5e97409ad45898af11cbc995b4ee8112d59095a28d376c935" + +[[package]] +name = "constant_time_eq" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "cookie" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94d4706de1b0fa5b132270cddffa8585166037822e260a944fe161acd137ca05" +dependencies = [ + "aes-gcm 0.9.4", + "base64 0.13.1", + "hkdf", + "hmac 0.12.1", + "percent-encoding", + "rand 0.8.5", + "sha2 0.10.6", + "subtle 2.4.1", + "time 0.3.17", + "version_check", +] + +[[package]] +name = "core-foundation" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" + +[[package]] +name = "cpufeatures" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49fc9a695bca7f35f5f4c15cddc84415f66a74ea78eef08e90c5024f2b540e23" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccaeedb56da03b09f598226e25e80088cb4cd25f316e6e4df7d695f0feeb1403" + +[[package]] +name = "crc32fast" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "criterion" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b01d6de93b2b6c65e17c634a26653a29d107b3c98c607c765bf38d041531cd8f" +dependencies = [ + "atty", + "cast", + "clap 2.34.0", + "criterion-plot", + "csv", + "itertools", + "lazy_static", + "num-traits", + "oorandom", + "plotters", + "rayon", + "regex", + "serde", + "serde_cbor", + "serde_derive", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2673cc8207403546f45f5fd319a974b1e6983ad1a3ee7e6041650013be041876" +dependencies = [ + "cast", + "itertools", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a9af1f4c2ef74bb8aa1f7e19706bc72d03598c8a570bb5de72243c7a9d9d5a" +dependencies = [ + "autocfg 1.1.0", + "cfg-if", + "crossbeam-utils", + "memoffset 0.7.1", + "scopeguard", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb766fa798726286dbbb842f174001dab8abc7b627a1dd86e0b7222a95d929f" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossterm" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85525306c4291d1b73ce93c8acf9c339f9b213aef6c1d85c3830cbf1c16325c" +dependencies = [ + "bitflags", + "crossterm_winapi", + "libc", + "mio 0.7.14", + "parking_lot 0.11.2", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2102ea4f781910f8a5b98dd061f4c2023f479ce7bb1236330099ceb5a93cf17" +dependencies = [ + "bitflags", + "crossterm_winapi", + "libc", + "mio 0.8.5", + "parking_lot 0.12.1", + "signal-hook", + "signal-hook-mio", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c" +dependencies = [ + "winapi", +] + +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + +[[package]] +name = "crypto-bigint" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2b4b23cddf68b89b8f8069890e8c270d54e2d5fe1b143820234805e4cb17ef" +dependencies = [ + "generic-array 0.14.6", + "rand_core 0.6.4", + "subtle 2.4.1", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array 0.14.6", + "typenum", +] + +[[package]] +name = "crypto-mac" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4434400df11d95d556bac068ddfedd482915eb18fe8bea89bc80b6e4b1c179e5" +dependencies = [ + "generic-array 0.12.4", + "subtle 1.0.0", +] + +[[package]] +name = "crypto-mac" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" +dependencies = [ + "generic-array 0.14.6", + "subtle 2.4.1", +] + +[[package]] +name = "cslice" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "697c714f50560202b1f4e2e09cd50a421881c83e9025db75d15f276616f04f40" + +[[package]] +name = "csv" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" +dependencies = [ + "bstr", + "csv-core", + "itoa 0.4.8", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" +dependencies = [ + "memchr", +] + +[[package]] +name = "ctr" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "049bb91fb4aaf0e3c7efa6cd5ef877dbbbd15b39dad06d9948de4ec8a75761ea" +dependencies = [ + "cipher 0.3.0", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher 0.4.3", +] + +[[package]] +name = "ctrlc" +version = "3.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d91974fbbe88ec1df0c24a4f00f99583667a7e2e6272b2b92d294d81e462173" +dependencies = [ + "nix 0.25.1", + "winapi", +] + +[[package]] +name = "curve25519-dalek" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26778518a7f6cffa1d25a44b602b62b979bd88adb9e99ffec546998cf3404839" +dependencies = [ + "byteorder", + "digest 0.8.1", + "rand_core 0.5.1", + "serde", + "subtle 2.4.1", + "zeroize", +] + +[[package]] +name = "cxx" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdf07d07d6531bfcdbe9b8b739b104610c6508dcc4d63b410585faf338241daf" +dependencies = [ + "cc", + "cxxbridge-flags", + "cxxbridge-macro", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2eb5b96ecdc99f72657332953d4d9c50135af1bac34277801cc3937906ebd39" +dependencies = [ + "cc", + "codespan-reporting", + "once_cell", + "proc-macro2 1.0.47", + "quote 1.0.21", + "scratch", + "syn 1.0.105", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac040a39517fd1674e0f32177648334b0f4074625b5588a64519804ba0553b12" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1362b0ddcfc4eb0a1f57b68bd77dd99f0e826958a96abd0ae9bd092e114ffed6" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "darling" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2 1.0.47", + "quote 1.0.21", + "strsim", + "syn 1.0.105", +] + +[[package]] +name = "darling_macro" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" +dependencies = [ + "darling_core", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "dashmap" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" +dependencies = [ + "cfg-if", + "hashbrown 0.12.3", + "lock_api", + "once_cell", + "parking_lot_core 0.9.5", +] + +[[package]] +name = "data-encoding" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d8666cb01533c39dde32bcbab8e227b4ed6679b2c925eba05feabea39508fb" + +[[package]] +name = "data-url" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a30bfce702bcfa94e906ef82421f2c0e61c076ad76030c16ee5d2e9a32fe193" +dependencies = [ + "matches", +] + +[[package]] +name = "debug_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2613f33760bd27a70ee84f5a8c0bd97e874fa6f89e205356ef8325786dd22cef" +dependencies = [ + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "debug_unreachable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a032eac705ca39214d169f83e3d3da290af06d8d1d344d1baad2fd002dca4b3" +dependencies = [ + "unreachable", +] + +[[package]] +name = "deno_ast" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42fb7189dc0564d7fc4d422868aad20cc6051b4469dad5a39a34bc4741cbc9ec" +dependencies = [ + "anyhow", + "base64 0.13.1", + "data-url", + "dprint-swc-ext", + "serde", + "swc_atoms", + "swc_bundler", + "swc_common", + "swc_ecma_ast", + "swc_ecma_codegen", + "swc_ecma_codegen_macros", + "swc_ecma_dep_graph", + "swc_ecma_loader", + "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_classes", + "swc_ecma_transforms_macros", + "swc_ecma_transforms_proposal", + "swc_ecma_transforms_react", + "swc_ecma_transforms_typescript", + "swc_ecma_utils", + "swc_ecma_visit", + "text_lines 0.4.1", + "url", +] + +[[package]] +name = "deno_broadcast_channel" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71feffc09d787b53b9e7d2a04edcc85a1809b51d6f02bae2e647bc1f3e349b1f" +dependencies = [ + "async-trait", + "deno_core", + "tokio", + "uuid 1.0.0", +] + +[[package]] +name = "deno_console" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d225d8d668a1bcfa33e3add7f5a62d55b2fffb3dcca8c0148b971958f808a2d" +dependencies = [ + "deno_core", +] + +[[package]] +name = "deno_core" +version = "0.146.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88475da37fe0544b7372fd4705560df496498eb5eeb40ce19bfe7787ed0600ca" +dependencies = [ + "anyhow", + "deno_ops", + "futures", + "indexmap", + "libc", + "log", + "once_cell", + "parking_lot 0.12.1", + "pin-project", + "serde", + "serde_json", + "serde_v8", + "sourcemap", + "url", + "v8", +] + +[[package]] +name = "deno_crypto" +version = "0.78.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "303b776f6495a6707952a30365c5d9b329fec59b809d79491d55ceaca579349e" +dependencies = [ + "aes 0.8.2", + "aes-gcm 0.10.0-pre", + "aes-kw", + "base64 0.13.1", + "block-modes 0.9.1", + "cbc", + "const-oid", + "ctr 0.9.2", + "deno_core", + "deno_web", + "elliptic-curve", + "num-traits", + "once_cell", + "p256", + "p384", + "rand 0.8.5", + "ring", + "rsa", + "sec1", + "serde", + "serde_bytes", + "sha-1 0.10.1", + "sha2 0.10.6", + "spki", + "tokio", + "uuid 1.0.0", +] + +[[package]] +name = "deno_emit" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e2a0076182afa41ee8e697e7646facdcc069cca89df3b12ca982b5069758f4" +dependencies = [ + "anyhow", + "base64 0.13.1", + "deno_ast", + "deno_graph", + "futures", + "parking_lot 0.11.2", +] + +[[package]] +name = "deno_fetch" +version = "0.87.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5196cf566f7eed31c43f12848a57e60ff8d7bab41983e31877007c9aa8e76758" +dependencies = [ + "bytes", + "data-url", + "deno_core", + "deno_tls", + "dyn-clone", + "http", + "reqwest", + "serde", + "tokio", + "tokio-stream", + "tokio-util 0.7.2", +] + +[[package]] +name = "deno_graph" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c6cc4d05b21c0dc80825a5dfb911ee09826004c89215c1bb92cbc1c44118d5" +dependencies = [ + "anyhow", + "cfg-if", + "data-url", + "deno_ast", + "futures", + "lazy_static", + "parking_lot 0.12.1", + "regex", + "ring", + "serde", + "serde_json", + "sourcemap", + "termcolor", + "url", +] + +[[package]] +name = "deno_http" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c983b2b2cf956e027192bdf2a7cfbd51ad0fc2b4be4c89c0f5a9e59b56b8f32e" +dependencies = [ + "async-compression", + "base64 0.13.1", + "brotli", + "bytes", + "cache_control", + "deno_core", + "deno_websocket", + "flate2", + "fly-accept-encoding", + "hyper", + "mime", + "percent-encoding", + "phf", + "ring", + "serde", + "tokio", + "tokio-util 0.7.2", +] + +[[package]] +name = "deno_net" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "701ed13edef61aa96d39e70b679fa01ba7508f645f65bccf28fb20eca25fa36d" +dependencies = [ + "deno_core", + "deno_tls", + "log", + "serde", + "socket2", + "tokio", + "trust-dns-proto", + "trust-dns-resolver", +] + +[[package]] +name = "deno_ops" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e217fd2f9a61bc581f6b13868a46ef800efb7532348fd86cc4fe49204d203ea6" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2 1.0.47", + "quote 1.0.21", + "regex", + "syn 1.0.105", +] + +[[package]] +name = "deno_tls" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10f604b5058cd533a00ec1f0dc9388bab42fb186912d789b6a9a8fd32af0d3a5" +dependencies = [ + "deno_core", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-pemfile", + "serde", + "webpki", + "webpki-roots", +] + +[[package]] +name = "deno_url" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a28c85d6e691a15cd8718c44c830a69d5a6c26d201f87d561a2bb63fe599cb" +dependencies = [ + "deno_core", + "serde", + "serde_repr", + "urlpattern", +] + +[[package]] +name = "deno_web" +version = "0.95.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ec62364ab724b3703e95482bf8172212cb1d2f86e7f18f41b0fefe3b8a8fddc" +dependencies = [ + "async-trait", + "base64-simd", + "deno_core", + "encoding_rs", + "flate2", + "serde", + "tokio", + "uuid 1.0.0", +] + +[[package]] +name = "deno_webidl" +version = "0.64.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c18838dcee75d21247e1235c81b457f4a1721602ca527bbfae2baff6e61dd2f" +dependencies = [ + "deno_core", +] + +[[package]] +name = "deno_websocket" +version = "0.69.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "909f4e8ec64d88f0414488553cd83615048c13b0958699b025404c2abaf07893" +dependencies = [ + "deno_core", + "deno_tls", + "http", + "hyper", + "serde", + "tokio", + "tokio-rustls", + "tokio-tungstenite", +] + +[[package]] +name = "deno_webstorage" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252f9c272c371e2bc3fc7578a6ba1ba21fb6f70139a7281a044d6e4869a05e88" +dependencies = [ + "deno_core", + "deno_web", + "rusqlite", + "serde", +] + +[[package]] +name = "der" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "derive_more" +version = "0.99.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +dependencies = [ + "convert_case", + "proc-macro2 1.0.47", + "quote 1.0.21", + "rustc_version 0.4.0", + "syn 1.0.105", +] + +[[package]] +name = "devise" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c7580b072f1c8476148f16e0a0d5dedddab787da98d86c5082c5e9ed8ab595" +dependencies = [ + "devise_codegen", + "devise_core", +] + +[[package]] +name = "devise_codegen" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "123c73e7a6e51b05c75fe1a1b2f4e241399ea5740ed810b0e3e6cacd9db5e7b2" +dependencies = [ + "devise_core", + "quote 1.0.21", +] + +[[package]] +name = "devise_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841ef46f4787d9097405cac4e70fb8644fc037b526e8c14054247c0263c400d0" +dependencies = [ + "bitflags", + "proc-macro2 1.0.47", + "proc-macro2-diagnostics", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "digest" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" +dependencies = [ + "generic-array 0.12.4", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array 0.14.6", +] + +[[package]] +name = "digest" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" +dependencies = [ + "block-buffer 0.10.3", + "crypto-common", + "subtle 2.4.1", +] + +[[package]] +name = "dirs" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" +dependencies = [ + "libc", + "redox_users 0.3.5", + "winapi", +] + +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users 0.4.3", + "winapi", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users 0.4.3", + "winapi", +] + +[[package]] +name = "discard" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" + +[[package]] +name = "dlopen" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e80ad39f814a9abe68583cd50a2d45c8a67561c3361ab8da240587dda80937" +dependencies = [ + "dlopen_derive", + "lazy_static", + "libc", + "winapi", +] + +[[package]] +name = "dlopen_derive" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f236d9e1b1fbd81cea0f9cbdc8dcc7e8ebcd80e6659cd7cb2ad5f6c05946c581" +dependencies = [ + "libc", + "quote 0.6.13", + "syn 0.15.44", +] + +[[package]] +name = "dprint-core" +version = "0.58.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bb2ee795c5be6f6512908e599a9747c6121aae982a535f0704db11130b38a08" +dependencies = [ + "anyhow", + "bumpalo", + "indexmap", + "rustc-hash", + "serde", +] + +[[package]] +name = "dprint-plugin-json" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db127f7ccb9b497b5b32e5e8eca4b19a7f191e38a3505195f029d5fbb728e51a" +dependencies = [ + "anyhow", + "dprint-core", + "jsonc-parser", + "serde", + "text_lines 0.4.1", +] + +[[package]] +name = "dprint-plugin-markdown" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "749753ef284b5eea8ab11e8baf01a735351c83747cdd72c5913e2351e6b8a309" +dependencies = [ + "anyhow", + "dprint-core", + "pulldown-cmark", + "regex", + "serde", +] + +[[package]] +name = "dprint-plugin-typescript" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a4ce966b327d5eba1df51bd9b0e373a741317f35a00abe7a71b01cfd582261" +dependencies = [ + "anyhow", + "deno_ast", + "dprint-core", + "rustc-hash", + "serde", +] + +[[package]] +name = "dprint-swc-ext" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e1b7708a102f7c085a1d51429a3664fe4dd3f6bf67091de83c9dae4dc700e2" +dependencies = [ + "bumpalo", + "num-bigint", + "rustc-hash", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "text_lines 0.4.1", +] + +[[package]] +name = "dyn-clone" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f94fa09c2aeea5b8839e414b7b841bf429fd25b9c522116ac97ee87856d88b2" + +[[package]] +name = "ecdsa" +version = "0.14.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413301934810f597c1d19ca71c8710e99a3f1ba28a0d2ebc01551a2daeea3c5c" +dependencies = [ + "der", + "elliptic-curve", + "rfc6979", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "1.0.0-pre.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978710b352437433c97b2bff193f2fb1dfd58a093f863dd95e225a19baa599a2" +dependencies = [ + "clear_on_drop", + "curve25519-dalek", + "rand 0.7.3", + "serde", + "sha2 0.8.2", +] + +[[package]] +name = "either" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797" + +[[package]] +name = "elliptic-curve" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" +dependencies = [ + "base16ct", + "crypto-bigint", + "der", + "digest 0.10.6", + "ff", + "generic-array 0.14.6", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle 2.4.1", + "zeroize", +] + +[[package]] +name = "encode_unicode" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" + +[[package]] +name = "encoding_rs" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "endian-type" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" + +[[package]] +name = "enum-as-inner" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21cdad81446a7f7dc43f6a77409efeb9733d2fa65553efef6018ef257c959b73" +dependencies = [ + "heck 0.4.0", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "enum_kind" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b940da354ae81ef0926c5eaa428207b8f4f091d3956c891dfbd124162bed99" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "env_logger" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "errno" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" +dependencies = [ + "errno-dragonfly", + "libc", + "winapi", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "error-chain" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9435d864e017c3c6afeac1654189b06cdb491cf2ff73dbf0d73b0f292f42ff8" + +[[package]] +name = "error-chain" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" +dependencies = [ + "backtrace", + "version_check", +] + +[[package]] +name = "error-code" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f18991e7bf11e7ffee451b5318b5c1a73c52d0d0ada6e5a3017c8c1ced6a21" +dependencies = [ + "libc", + "str-buf", +] + +[[package]] +name = "failure" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" +dependencies = [ + "backtrace", +] + +[[package]] +name = "fake-simd" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499" +dependencies = [ + "instant", +] + +[[package]] +name = "fd-lock" +version = "3.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb21c69b9fea5e15dbc1049e4b77145dd0ba1c84019c488102de0dc4ea4b0a27" +dependencies = [ + "cfg-if", + "rustix", + "windows-sys 0.42.0", +] + +[[package]] +name = "ff" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d013fc25338cc558c5c2cfbad646908fb23591e2404481826742b651c9af7160" +dependencies = [ + "rand_core 0.6.4", + "subtle 2.4.1", +] + +[[package]] +name = "figment" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e56602b469b2201400dec66a66aec5a9b8761ee97cd1b8c96ab2483fcc16cc9" +dependencies = [ + "atomic", + "pear", + "serde", + "toml 0.5.9", + "uncased", + "version_check", +] + +[[package]] +name = "filetime" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e884668cd0c7480504233e951174ddc3b382f7c2666e3b7310b5c4e7b0c37f9" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.2.16", + "windows-sys 0.42.0", +] + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + +[[package]] +name = "flate2" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" +dependencies = [ + "crc32fast", + "miniz_oxide 0.6.2", +] + +[[package]] +name = "flume" +version = "0.10.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1657b4441c3403d9f7b3409e47575237dac27b1b5726df654a6ecbf92f0f7577" +dependencies = [ + "futures-core", + "futures-sink", + "nanorand", + "pin-project", + "spin 0.9.4", +] + +[[package]] +name = "fly-accept-encoding" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3afa7516fdcfd8e5e93a938f8fec857785ced190a1f62d842d1fe1ffbe22ba8" +dependencies = [ + "http", + "itertools", + "thiserror", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "from_variant" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0981e470d2ab9f643df3921d54f1952ea100c39fdb6a3fdc820e20d2291df6c" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "fs3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb17cf6ed704f72485332f6ab65257460c4f9f3083934cf402bf9f5b3b600a90" +dependencies = [ + "libc", + "rustc_version 0.2.3", + "winapi", +] + +[[package]] +name = "fsevent" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8836d1f147a0a195bf517a5fd211ea7023d19ced903135faf6c4504f2cf8775f" +dependencies = [ + "bitflags", + "fsevent-sys 4.1.0", +] + +[[package]] +name = "fsevent-sys" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca6f5e6817058771c10f0eb0f05ddf1e35844266f972004fe8e4b21fda295bd5" +dependencies = [ + "libc", +] + +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + +[[package]] +name = "fslock" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57eafdd0c16f57161105ae1b98a1238f97645f2f588438b2949c99a2af9616bf" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" + +[[package]] +name = "futures" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" + +[[package]] +name = "futures-executor" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb" + +[[package]] +name = "futures-macro" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "futures-sink" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9" + +[[package]] +name = "futures-task" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" + +[[package]] +name = "futures-util" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "fwdansi" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c1f5787fe85505d1f7777268db5103d80a7a374d2316a7ce262e57baf8f208" +dependencies = [ + "memchr", + "termcolor", +] + +[[package]] +name = "generator" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d266041a359dfa931b370ef684cceb84b166beb14f7f0421f4a6a3d0c446d12e" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows", +] + +[[package]] +name = "generic-array" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" +dependencies = [ + "typenum", +] + +[[package]] +name = "generic-array" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1583cc1656d7839fd3732b80cf4f38850336cdb9b8ded1cd399ca62958de3c99" +dependencies = [ + "opaque-debug 0.3.0", + "polyval", +] + +[[package]] +name = "gimli" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22030e2c5a68ec659fde1e949a745124b48e6fa8b045b7ed5bd1fe4ccc5c4e5d" + +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + +[[package]] +name = "group" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfbfb3a6cfbd390d5c9564ab283a0349b9b9fcd46a706c1eb10e0db70bfbac7" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle 2.4.1", +] + +[[package]] +name = "h2" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util 0.7.2", + "tracing", +] + +[[package]] +name = "half" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashlink" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7249a3129cbc1ffccd74857f81464a323a152173cdb134e0fd81bc803b29facf" +dependencies = [ + "hashbrown 0.11.2", +] + +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "hex" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hiro-system-kit" +version = "0.1.0" +dependencies = [ + "ansi_term", + "atty", + "futures", + "lazy_static", + "slog", + "slog-async", + "slog-atomic", + "slog-json", + "slog-scope", + "slog-term", + "tokio", +] + +[[package]] +name = "hkdf" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" +dependencies = [ + "hmac 0.12.1", +] + +[[package]] +name = "hmac" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dcb5e64cda4c23119ab41ba960d1e170a774c8e4b9d9e6a9bc18aabf5e59695" +dependencies = [ + "crypto-mac 0.7.0", + "digest 0.8.1", +] + +[[package]] +name = "hmac" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "126888268dcc288495a26bf004b38c5fdbb31682f992c84ceb046a1f0fe38840" +dependencies = [ + "crypto-mac 0.8.0", + "digest 0.9.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.6", +] + +[[package]] +name = "hmac-drbg" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e570451493f10f6581b48cdd530413b63ea9e780f544bfd3bdcaa0d89d1a7b" +dependencies = [ + "digest 0.8.1", + "generic-array 0.12.4", + "hmac 0.7.1", +] + +[[package]] +name = "hmac-drbg" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17ea0a1394df5b6574da6e0c1ade9e78868c9fb0a4e5ef4428e32da4676b85b1" +dependencies = [ + "digest 0.9.0", + "generic-array 0.14.6", + "hmac 0.8.1", +] + +[[package]] +name = "hostname" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c731c3e10504cc8ed35cfe2f1db4c9274c3d35fa486e3b31df46f068ef3e867" +dependencies = [ + "libc", + "match_cfg", + "winapi", +] + +[[package]] +name = "http" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399" +dependencies = [ + "bytes", + "fnv", + "itoa 1.0.4", +] + +[[package]] +name = "http-body" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "hyper" +version = "0.14.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "034711faac9d2166cb1baf1a2fb0b60b1f277f8492fd72176c17f3515e1abd3c" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa 1.0.4", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c" +dependencies = [ + "http", + "hyper", + "rustls", + "tokio", + "tokio-rustls", +] + +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "hyperlocal" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fafdf7b2b2de7c9784f76e02c0935e65a8117ec3b768644379983ab333ac98c" +dependencies = [ + "futures-util", + "hex 0.4.3", + "hyper", + "pin-project", + "tokio", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +dependencies = [ + "cxx", + "cxx-build", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" +dependencies = [ + "matches", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "if_chain" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" + +[[package]] +name = "import_map" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b827962ca5aa6d5bbe313c14e73d7cc517487fa3bad380bb6bdbd8421e591a29" +dependencies = [ + "indexmap", + "log", + "serde", + "serde_json", + "url", +] + +[[package]] +name = "indexmap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" +dependencies = [ + "autocfg 1.1.0", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + +[[package]] +name = "inotify" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff" +dependencies = [ + "bitflags", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" +dependencies = [ + "libc", +] + +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "block-padding 0.3.2", + "generic-array 0.14.6", +] + +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "integer-sqrt" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "276ec31bcb4a9ee45f58bec6f9ec700ae4cf4f4f8f2fa7e06cb406bd5ffdd770" +dependencies = [ + "num-traits", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46112a93252b123d31a119a8d1a1ac19deac4fac6e0e8b0df58f0d4e5870e63c" +dependencies = [ + "libc", + "windows-sys 0.42.0", +] + +[[package]] +name = "ipconfig" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd302af1b90f2463a98fa5ad469fc212c8e3175a41c3068601bfa2727591c5be" +dependencies = [ + "socket2", + "widestring", + "winapi", + "winreg", +] + +[[package]] +name = "ipnet" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec947b7a4ce12e3b87e353abae7ce124d025b6c7d6c5aea5cc0bcf92e9510ded" + +[[package]] +name = "is-macro" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c068d4c6b922cd6284c609cfa6dec0e41615c9c5a1a4ba729a970d8daba05fb" +dependencies = [ + "Inflector", + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + +[[package]] +name = "itoa" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" + +[[package]] +name = "jobserver" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "068b1ee6743e4d11fb9c6a1e6064b3693a1b600e7f5f5988047d98b3dc9fb90b" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "json" +version = "0.11.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92c245af8786f6ac35f95ca14feca9119e71339aaab41e878e7cdd655c97e9e5" + +[[package]] +name = "jsonc-parser" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccff81ff106af12c93c06935c50ee0723325095e8cbb8c0b41ed276b9469c4cb" +dependencies = [ + "serde_json", +] + +[[package]] +name = "jsonrpc" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8423b78fc94d12ef1a4a9d13c348c9a78766dda0cc18817adf0faf77e670c8" +dependencies = [ + "base64-compat", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "keccak" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3afef3b6eff9ce9d8ff9b3601125eec7f0c8cbac7abd14f355d053fa56c98768" +dependencies = [ + "cpufeatures", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +dependencies = [ + "spin 0.5.2", +] + +[[package]] +name = "lexical" +version = "6.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7aefb36fd43fef7003334742cbf77b243fcd36418a1d1bdd480d613a67968f6" +dependencies = [ + "lexical-core", +] + +[[package]] +name = "lexical-core" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cde5de06e8d4c2faabc400238f9ae1c74d5412d03a7bd067645ccbc47070e46" +dependencies = [ + "lexical-parse-float", + "lexical-parse-integer", + "lexical-util", + "lexical-write-float", + "lexical-write-integer", +] + +[[package]] +name = "lexical-parse-float" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683b3a5ebd0130b8fb52ba0bdc718cc56815b6a097e28ae5a6997d0ad17dc05f" +dependencies = [ + "lexical-parse-integer", + "lexical-util", + "static_assertions", +] + +[[package]] +name = "lexical-parse-integer" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d0994485ed0c312f6d965766754ea177d07f9c00c9b82a5ee62ed5b47945ee9" +dependencies = [ + "lexical-util", + "static_assertions", +] + +[[package]] +name = "lexical-util" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5255b9ff16ff898710eb9eb63cb39248ea8a5bb036bea8085b1a767ff6c4e3fc" +dependencies = [ + "static_assertions", +] + +[[package]] +name = "lexical-write-float" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accabaa1c4581f05a3923d1b4cfd124c329352288b7b9da09e766b0668116862" +dependencies = [ + "lexical-util", + "lexical-write-integer", + "static_assertions", +] + +[[package]] +name = "lexical-write-integer" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b6f3d1f4422866b68192d62f77bc5c700bee84f3069f2469d7bc8c77852446" +dependencies = [ + "lexical-util", + "static_assertions", +] + +[[package]] +name = "libc" +version = "0.2.138" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8" + +[[package]] +name = "libloading" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "351a32417a12d5f7e82c368a66781e307834dae04c6ce0cd4456d52989229883" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libm" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" + +[[package]] +name = "libsecp256k1" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc1e2c808481a63dc6da2074752fdd4336a3c8fcc68b83db6f1fd5224ae7962" +dependencies = [ + "arrayref", + "crunchy", + "digest 0.8.1", + "hmac-drbg 0.2.0", + "rand 0.7.3", + "sha2 0.8.2", + "subtle 2.4.1", + "typenum", +] + +[[package]] +name = "libsecp256k1" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd1137239ab33b41aa9637a88a28249e5e70c40a42ccc92db7f12cc356c1fcd7" +dependencies = [ + "arrayref", + "base64 0.12.3", + "digest 0.9.0", + "hmac-drbg 0.3.0", + "libsecp256k1-core 0.2.2", + "libsecp256k1-gen-ecmult 0.2.1", + "libsecp256k1-gen-genmult 0.2.1", + "rand 0.7.3", + "serde", + "sha2 0.9.9", + "typenum", +] + +[[package]] +name = "libsecp256k1" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95b09eff1b35ed3b33b877ced3a691fc7a481919c7e29c53c906226fcf55e2a1" +dependencies = [ + "arrayref", + "base64 0.13.1", + "digest 0.9.0", + "hmac-drbg 0.3.0", + "libsecp256k1-core 0.3.0", + "libsecp256k1-gen-ecmult 0.3.0", + "libsecp256k1-gen-genmult 0.3.0", + "rand 0.8.5", + "serde", + "sha2 0.9.9", + "typenum", +] + +[[package]] +name = "libsecp256k1-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0f6ab710cec28cef759c5f18671a27dae2a5f952cdaaee1d8e2908cb2478a80" +dependencies = [ + "crunchy", + "digest 0.9.0", + "subtle 2.4.1", +] + +[[package]] +name = "libsecp256k1-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be9b9bb642d8522a44d533eab56c16c738301965504753b03ad1de3425d5451" +dependencies = [ + "crunchy", + "digest 0.9.0", + "subtle 2.4.1", +] + +[[package]] +name = "libsecp256k1-gen-ecmult" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccab96b584d38fac86a83f07e659f0deafd0253dc096dab5a36d53efe653c5c3" +dependencies = [ + "libsecp256k1-core 0.2.2", +] + +[[package]] +name = "libsecp256k1-gen-ecmult" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3038c808c55c87e8a172643a7d87187fc6c4174468159cb3090659d55bcb4809" +dependencies = [ + "libsecp256k1-core 0.3.0", +] + +[[package]] +name = "libsecp256k1-gen-genmult" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67abfe149395e3aa1c48a2beb32b068e2334402df8181f818d3aee2b304c4f5d" +dependencies = [ + "libsecp256k1-core 0.2.2", +] + +[[package]] +name = "libsecp256k1-gen-genmult" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db8d6ba2cec9eacc40e6e8ccc98931840301f1006e95647ceb2dd5c3aa06f7c" +dependencies = [ + "libsecp256k1-core 0.3.0", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898745e570c7d0453cc1fbc4a701eb6c662ed54e8fec8b7d14be137ebeeb9d14" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "link-cplusplus" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9272ab7b96c9046fbc5bc56c06c117cb639fe2d509df0c421cad82d2915cf369" +dependencies = [ + "cc", +] + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "linux-raw-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f9f08d8963a6c613f4b1a78f4f4a4dbfadf8e6545b2d72861731e4858b8b47f" + +[[package]] +name = "lock_api" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +dependencies = [ + "autocfg 1.1.0", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", + "serde", +] + +[[package]] +name = "loom" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "lru-cache" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c" +dependencies = [ + "linked-hash-map", +] + +[[package]] +name = "lsp-types" +version = "0.93.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be6e9c7e2d18f651974370d7aff703f9513e0df6e464fd795660edc77e6ca51" +dependencies = [ + "bitflags", + "serde", + "serde_json", + "serde_repr", + "url", +] + +[[package]] +name = "lzzzz" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8014d1362004776e6a91e4c15a3aa7830d1b6650a075b51a9969ebb6d6af13bc" +dependencies = [ + "cc", +] + +[[package]] +name = "mac_address" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b238e3235c8382b7653c6408ed1b08dd379bdb9fdf990fb0bbae3db2cc0ae963" +dependencies = [ + "nix 0.23.2", + "winapi", +] + +[[package]] +name = "match_cfg" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4" + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matches" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg 1.1.0", +] + +[[package]] +name = "memoffset" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" +dependencies = [ + "autocfg 1.1.0", +] + +[[package]] +name = "memzero" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93c0d11ac30a033511ae414355d80f70d9f29a44a49140face477117a1ee90db" + +[[package]] +name = "metadeps" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b122901b3a675fac8cecf68dcb2f0d3036193bc861d1ac0e1c337f7d5254c2" +dependencies = [ + "error-chain 0.10.0", + "pkg-config", + "toml 0.2.1", +] + +[[package]] +name = "mime" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" + +[[package]] +name = "miniz_oxide" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96590ba8f175222643a85693f33d26e9c8a015f599c216509b1a6894af675d34" +dependencies = [ + "adler", +] + +[[package]] +name = "miniz_oxide" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc" +dependencies = [ + "libc", + "log", + "miow", + "ntapi", + "winapi", +] + +[[package]] +name = "mio" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de" +dependencies = [ + "libc", + "log", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys 0.42.0", +] + +[[package]] +name = "miow" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21" +dependencies = [ + "winapi", +] + +[[package]] +name = "mitata" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21fd49a3bd69c5be5d2c21899e2995ed99193b48e2c9f3ac09596a0d69f7fa79" +dependencies = [ + "clap 3.2.23", +] + +[[package]] +name = "multer" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ed4198ce7a4cbd2a57af78d28c6fbb57d81ac5f1d6ad79ac6c5587419cbdf22" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "log", + "memchr", + "mime", + "spin 0.9.4", + "tokio", + "tokio-util 0.7.2", + "version_check", +] + +[[package]] +name = "nanorand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a51313c5820b0b02bd422f4b44776fbf47961755c74ce64afc73bfad10226c3" +dependencies = [ + "getrandom 0.2.8", +] + +[[package]] +name = "native-tls" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "neon" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e85820b585bf3360bf158ac87a75764c48e361c91bbeb69873e6613cc78c023" +dependencies = [ + "cslice", + "neon-build", + "neon-macros", + "neon-runtime", + "semver 0.9.0", + "smallvec", +] + +[[package]] +name = "neon-build" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad9febc63f515156d4311a0c43899d3ace46352ecdd591c21b98ca3974f2a0d0" + +[[package]] +name = "neon-macros" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "987f12c91eb6ce0b67819f7c5fb4d391de64cf411c605ed027f03507a33943b2" +dependencies = [ + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "neon-runtime" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02662cd2e62b131937bdef85d0918b05bc3c204daf4c64af62845403eccb60f3" +dependencies = [ + "cfg-if", + "libloading", + "smallvec", +] + +[[package]] +name = "netif" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29a01b9f018d6b7b277fef6c79fdbd9bf17bb2d1e298238055cafab49baa5ee" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54" + +[[package]] +name = "nibble_vec" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" +dependencies = [ + "smallvec", +] + +[[package]] +name = "nix" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f3790c00a0150112de0f4cd161e3d7fc4b2d8a5542ffc35f099a2562aecb35c" +dependencies = [ + "bitflags", + "cc", + "cfg-if", + "libc", + "memoffset 0.6.5", +] + +[[package]] +name = "nix" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "195cdbc1741b8134346d515b3a56a1c94b0912758009cfd53f99ea0f57b065fc" +dependencies = [ + "bitflags", + "cfg-if", + "libc", + "memoffset 0.6.5", +] + +[[package]] +name = "nix" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" +dependencies = [ + "autocfg 1.1.0", + "bitflags", + "cfg-if", + "libc", +] + +[[package]] +name = "node_resolver" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1012fcb4f5cc14c272731f4baf6ba8a2d40c650908f4d2531f7ed17f214e5ae" +dependencies = [ + "anyhow", + "path-clean", + "serde", + "serde_json", +] + +[[package]] +name = "notify" +version = "5.0.0-pre.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebe7699a0f8c5759450716ee03d231685c22b4fe8f406c42c22e0ad94d40ce7" +dependencies = [ + "anymap", + "bitflags", + "crossbeam-channel", + "filetime", + "fsevent", + "fsevent-sys 3.1.0", + "inotify", + "libc", + "mio 0.7.14", + "walkdir", + "winapi", +] + +[[package]] +name = "ntapi" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28774a7fd2fbb4f0babd8237ce554b73af68021b5f695a3cebd6c59bac0980f" +dependencies = [ + "winapi", +] + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "num" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36" +dependencies = [ + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" +dependencies = [ + "autocfg 1.1.0", + "num-integer", + "num-traits", + "serde", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2399c9463abc5f909349d8aa9ba080e0b88b3ce2885389b60b993f39b1a56905" +dependencies = [ + "byteorder", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.5", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-complex" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" +dependencies = [ + "autocfg 1.1.0", + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg 1.1.0", + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg 1.1.0", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" +dependencies = [ + "autocfg 1.1.0", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg 1.1.0", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +dependencies = [ + "libc", +] + +[[package]] +name = "object" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" +dependencies = [ + "memchr", +] + +[[package]] +name = "okapi" +version = "0.7.0-rc.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce66b6366e049880a35c378123fddb630b1a1a3c37fa1ca70caaf4a09f6e2893" +dependencies = [ + "log", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "once_cell" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" + +[[package]] +name = "oorandom" +version = "11.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" + +[[package]] +name = "opaque-debug" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" + +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + +[[package]] +name = "openssl" +version = "0.10.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b102428fd03bc5edf97f62620f7298614c45cedf287c271e7ed450bbaf83f2e1" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23bbbf7854cd45b83958ebe919f0e8e516793727652e27fda10a8384cfc790b7" +dependencies = [ + "autocfg 1.1.0", + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "os_pipe" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6a252f1f8c11e84b3ab59d7a488e48e4478a93937e027076638c49536204639" +dependencies = [ + "libc", + "windows-sys 0.42.0", +] + +[[package]] +name = "os_str_bytes" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee" + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "p256" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" +dependencies = [ + "ecdsa", + "elliptic-curve", + "sha2 0.10.6", +] + +[[package]] +name = "p384" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc8c5bf642dde52bb9e87c0ecd8ca5a76faac2eeed98dedb7c717997e1080aa" +dependencies = [ + "ecdsa", + "elliptic-curve", + "sha2 0.10.6", +] + +[[package]] +name = "parking_lot" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" +dependencies = [ + "instant", + "lock_api", + "parking_lot_core 0.8.5", +] + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core 0.9.5", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216" +dependencies = [ + "cfg-if", + "instant", + "libc", + "redox_syscall 0.2.16", + "smallvec", + "winapi", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.2.16", + "smallvec", + "windows-sys 0.42.0", +] + +[[package]] +name = "password-hash" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle 2.4.1", +] + +[[package]] +name = "path-clean" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecba01bf2678719532c5e3059e0b5f0811273d94b397088b82e3bd0a78c78fdd" + +[[package]] +name = "pathdiff" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" + +[[package]] +name = "pbkdf2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +dependencies = [ + "digest 0.10.6", + "hmac 0.12.1", + "password-hash", + "sha2 0.10.6", +] + +[[package]] +name = "pear" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15e44241c5e4c868e3eaa78b7c1848cadd6344ed4f54d029832d32b415a58702" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82a5ca643c2303ecb740d506539deba189e16f2754040a42901cd8105d0282d0" +dependencies = [ + "proc-macro2 1.0.47", + "proc-macro2-diagnostics", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "pem-rfc7468" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d159833a9105500e0398934e205e0773f0b27529557134ecfc51c27646adac" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" + +[[package]] +name = "pest" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc8bed3549e0f9b0a2a78bf7c0018237a2cdf085eecbbc048e52612438e4e9d0" +dependencies = [ + "thiserror", + "ucd-trie", +] + +[[package]] +name = "petgraph" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5014253a1331579ce62aa67443b4a658c5e7dd03d4bc6d302b94474888143" +dependencies = [ + "fixedbitset", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_macros", + "phf_shared", + "proc-macro-hack", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared", + "rand 0.8.5", +] + +[[package]] +name = "phf_macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro-hack", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8bcd96cb740d03149cbad5518db9fd87126a10ab519c011893b1754134c468" + +[[package]] +name = "pin-project" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkcs1" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff33bdbdfc54cc98a2eca766ebdec3e1b8fb7387523d5c9c9a2891da856f719" +dependencies = [ + "der", + "pkcs8", + "spki", + "zeroize", +] + +[[package]] +name = "pkcs8" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" + +[[package]] +name = "plotters" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2538b639e642295546c50fcd545198c9d64ee2a38620a628724a3b266d5fbf97" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "193228616381fecdc1224c62e96946dfbc73ff4384fba576e052ff8c1bea8142" + +[[package]] +name = "plotters-svg" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9a81d2759aae1dae668f783c308bc5c8ebd191ff4184aaa1b37f65a6ae5a56f" +dependencies = [ + "plotters-backend", +] + +[[package]] +name = "pmutil" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3894e5d549cccbe44afecf72922f277f603cd4bb0219c8342631ef18fffbe004" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "polyval" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8419d2b623c7c0896ff2d5d96e2cb4ede590fed28fcc34934f4c33c036e620a1" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug 0.3.0", + "universal-hash", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "prettytable-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fd04b170004fa2daccf418a7f8253aaf033c27760b5f225889024cf66d7ac2e" +dependencies = [ + "atty", + "csv", + "encode_unicode", + "lazy_static", + "term 0.5.2", + "unicode-width", +] + +[[package]] +name = "proc-macro-crate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eda0fc3b0fb7c975631757e14d9049da17374063edb6ebbcbc54d880d4fe94e9" +dependencies = [ + "once_cell", + "thiserror", + "toml 0.5.9", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "version_check", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +dependencies = [ + "unicode-xid 0.1.0", +] + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bf29726d67464d49fa6224a1d07936a8c08bb3fba727c7493f6cf1616fdaada" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", + "version_check", + "yansi", +] + +[[package]] +name = "psm" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5787f7cda34e3033a72192c018bc5883100330f362ef279a8cbccfce8bb4e874" +dependencies = [ + "cc", +] + +[[package]] +name = "pulldown-cmark" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d9cc634bc78768157b5cbfe988ffcd1dcba95cd2b2f03a88316c08c6d00ed63" +dependencies = [ + "bitflags", + "memchr", + "unicase", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +dependencies = [ + "proc-macro2 0.4.30", +] + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2 1.0.47", +] + +[[package]] +name = "radix_fmt" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce082a9940a7ace2ad4a8b7d0b1eac6aa378895f18be598230c5f2284ac05426" + +[[package]] +name = "radix_trie" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd" +dependencies = [ + "endian-type", + "nibble_vec", +] + +[[package]] +name = "rand" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" +dependencies = [ + "autocfg 0.1.8", + "libc", + "rand_chacha 0.1.1", + "rand_core 0.4.2", + "rand_hc 0.1.0", + "rand_isaac", + "rand_jitter", + "rand_os", + "rand_pcg 0.1.2", + "rand_xorshift", + "winapi", +] + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc 0.2.0", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" +dependencies = [ + "autocfg 0.1.8", + "rand_core 0.3.1", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +dependencies = [ + "rand_core 0.4.2", +] + +[[package]] +name = "rand_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.8", +] + +[[package]] +name = "rand_hc" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" +dependencies = [ + "rand_core 0.3.1", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_isaac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" +dependencies = [ + "rand_core 0.3.1", +] + +[[package]] +name = "rand_jitter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" +dependencies = [ + "libc", + "rand_core 0.4.2", + "winapi", +] + +[[package]] +name = "rand_os" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" +dependencies = [ + "cloudabi", + "fuchsia-cprng", + "libc", + "rand_core 0.4.2", + "rdrand", + "winapi", +] + +[[package]] +name = "rand_pcg" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" +dependencies = [ + "autocfg 0.1.8", + "rand_core 0.4.2", +] + +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand_seeder" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf2890aaef0aa82719a50e808de264f9484b74b442e1a3a0e5ee38243ac40bdb" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "rand_xorshift" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" +dependencies = [ + "rand_core 0.3.1", +] + +[[package]] +name = "rayon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e060280438193c554f654141c9ea9417886713b7acd75974c85b18a69a88e0b" +dependencies = [ + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cac410af5d00ab6884528b4ab69d1e8e146e8d471201800fa1b4524126de6ad3" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + +[[package]] +name = "rdrand" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" +dependencies = [ + "rand_core 0.3.1", +] + +[[package]] +name = "redis" +version = "0.21.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "571c252c68d09a2ad3e49edd14e9ee48932f3e0f27b06b4ea4c9b2a706d31103" +dependencies = [ + "async-trait", + "combine", + "itoa 1.0.4", + "percent-encoding", + "ryu", + "sha1", + "url", +] + +[[package]] +name = "redox_syscall" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" +dependencies = [ + "getrandom 0.1.16", + "redox_syscall 0.1.57", + "rust-argon2", +] + +[[package]] +name = "redox_users" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +dependencies = [ + "getrandom 0.2.8", + "redox_syscall 0.2.16", + "thiserror", +] + +[[package]] +name = "ref-cast" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53b15debb4f9d60d767cd8ca9ef7abb2452922f3214671ff052defc7f3502c44" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abfa8511e9e94fd3de6585a3d3cd00e01ed556dc9814829280af0e8dc72a8f36" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "regex" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" + +[[package]] +name = "relative-path" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0df32d82cedd1499386877b062ebe8721f806de80b08d183c70184ef17dd1d42" + +[[package]] +name = "remove_dir_all" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" +dependencies = [ + "winapi", +] + +[[package]] +name = "reqwest" +version = "0.11.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68cc60575865c7831548863cc02356512e3f1dc2f3f82cb837d7fc4cc8f3c97c" +dependencies = [ + "async-compression", + "base64 0.13.1", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "hyper", + "hyper-rustls", + "hyper-tls", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-native-tls", + "tokio-rustls", + "tokio-util 0.7.2", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", + "winreg", +] + +[[package]] +name = "resolv-conf" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52e44394d2086d010551b14b53b1f24e31647570cd1deb0379e2c21b329aba00" +dependencies = [ + "hostname", + "quick-error", +] + +[[package]] +name = "retain_mut" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4389f1d5789befaf6029ebd9f7dac4af7f7e3d61b69d4f30e2ac02b57e7712b0" + +[[package]] +name = "rfc6979" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb" +dependencies = [ + "crypto-bigint", + "hmac 0.12.1", + "zeroize", +] + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin 0.5.2", + "untrusted", + "web-sys", + "winapi", +] + +[[package]] +name = "ripemd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.6", +] + +[[package]] +name = "ripemd160" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad5112e0dbbb87577bfbc56c42450235e3012ce336e29c5befd7807bd626da4a" +dependencies = [ + "block-buffer 0.7.3", + "digest 0.8.1", + "opaque-debug 0.2.3", +] + +[[package]] +name = "ripemd160" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eca4ecc81b7f313189bf73ce724400a07da2a6dac19588b03c8bd76a2dcc251" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + +[[package]] +name = "rocket" +version = "0.5.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98ead083fce4a405feb349cf09abdf64471c6077f14e0ce59364aa90d4b99317" +dependencies = [ + "async-stream", + "async-trait", + "atomic", + "atty", + "binascii", + "bytes", + "either", + "figment", + "futures", + "indexmap", + "log", + "memchr", + "multer", + "num_cpus", + "parking_lot 0.12.1", + "pin-project-lite", + "rand 0.8.5", + "ref-cast", + "rocket_codegen", + "rocket_http", + "serde", + "serde_json", + "state", + "tempfile", + "time 0.3.17", + "tokio", + "tokio-stream", + "tokio-util 0.7.2", + "ubyte", + "version_check", + "yansi", +] + +[[package]] +name = "rocket_codegen" +version = "0.5.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6aeb6bb9c61e9cd2c00d70ea267bf36f76a4cc615e5908b349c2f9d93999b47" +dependencies = [ + "devise", + "glob", + "indexmap", + "proc-macro2 1.0.47", + "quote 1.0.21", + "rocket_http", + "syn 1.0.105", + "unicode-xid 0.2.4", +] + +[[package]] +name = "rocket_http" +version = "0.5.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ded65d127954de3c12471630bf4b81a2792f065984461e65b91d0fdaafc17a2" +dependencies = [ + "cookie", + "either", + "futures", + "http", + "hyper", + "indexmap", + "log", + "memchr", + "pear", + "percent-encoding", + "pin-project-lite", + "ref-cast", + "serde", + "smallvec", + "stable-pattern", + "state", + "time 0.3.17", + "tokio", + "uncased", +] + +[[package]] +name = "rocket_okapi" +version = "0.8.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "489f4f5b120762f7974e65b919fc462d0660fd8b839026d8985b850fe5acccb0" +dependencies = [ + "either", + "log", + "okapi", + "rocket", + "rocket_okapi_codegen", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "rocket_okapi_codegen" +version = "0.8.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54f94d1ffe41472e08463d7a2674f1db04dc4df745285e8369b33d3cfd6b0308" +dependencies = [ + "darling", + "proc-macro2 1.0.47", + "quote 1.0.21", + "rocket_http", + "syn 1.0.105", +] + +[[package]] +name = "rsa" +version = "0.7.0-pre" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6168b9a0f38e487db90dc109ad6d8f37fc5590183b7bfe8d8687e0b86116d53f" +dependencies = [ + "byteorder", + "digest 0.10.6", + "num-bigint-dig", + "num-integer", + "num-iter", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "smallvec", + "subtle 2.4.1", + "zeroize", +] + +[[package]] +name = "rstest" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2288c66aeafe3b2ed227c981f364f9968fa952ef0b30e84ada4486e7ee24d00a" +dependencies = [ + "cfg-if", + "proc-macro2 1.0.47", + "quote 1.0.21", + "rustc_version 0.4.0", + "syn 1.0.105", +] + +[[package]] +name = "rstest_reuse" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32c6cfaae58c048728261723a72b80a0aa9f3768e9a7da3b302a24d262525219" +dependencies = [ + "quote 1.0.21", + "rustc_version 0.3.3", + "syn 1.0.105", +] + +[[package]] +name = "rusqlite" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85127183a999f7db96d1a976a309eebbfb6ea3b0b400ddd8340190129de6eb7a" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "memchr", + "serde_json", + "smallvec", +] + +[[package]] +name = "rust-argon2" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" +dependencies = [ + "base64 0.13.1", + "blake2b_simd", + "constant_time_eq", + "crossbeam-utils", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef03e0a2b150c7a90d01faf6254c9c48a41e95fb2a8c2ac1c6f0d2b9aefc342" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver 0.9.0", +] + +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver 1.0.14", +] + +[[package]] +name = "rustix" +version = "0.36.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3807b5d10909833d3e9acd1eb5fb988f79376ff10fce42937de71a449c4c588" +dependencies = [ + "bitflags", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys", + "windows-sys 0.42.0", +] + +[[package]] +name = "rustls" +version = "0.20.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "539a2bfe908f471bfa933876bd1eb6a19cf2176d375f82ef7f99530a40e48c2c" +dependencies = [ + "log", + "ring", + "sct", + "webpki", +] + +[[package]] +name = "rustls-native-certs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0167bac7a9f490495f3c33013e7722b53cb087ecbe082fb0c6387c96f634ea50" +dependencies = [ + "openssl-probe", + "rustls-pemfile", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0864aeff53f8c05aa08d86e5ef839d3dfcf07aeba2db32f12db0ef716e87bd55" +dependencies = [ + "base64 0.13.1", +] + +[[package]] +name = "rustversion" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" + +[[package]] +name = "rustyline" +version = "9.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db7826789c0e25614b03e5a54a0717a86f9ff6e6e5247f92b369472869320039" +dependencies = [ + "bitflags", + "cfg-if", + "clipboard-win", + "dirs-next", + "fd-lock", + "libc", + "log", + "memchr", + "nix 0.23.2", + "radix_trie", + "scopeguard", + "smallvec", + "unicode-segmentation", + "unicode-width", + "utf8parse", + "winapi", +] + +[[package]] +name = "ryu" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" +dependencies = [ + "lazy_static", + "windows-sys 0.36.1", +] + +[[package]] +name = "schemars" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a5fb6c61f29e723026dc8e923d94c694313212abbecbbe5f55a7748eec5b307" +dependencies = [ + "dyn-clone", + "indexmap", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f188d036977451159430f3b8dc82ec76364a42b7e289c2b18a9a18f4470058e9" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "serde_derive_internals", + "syn 1.0.105", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "scratch" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8132065adcfd6e02db789d9285a0deb2f3fcb04002865ab67d5fb103533898" + +[[package]] +name = "sct" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "sec1" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" +dependencies = [ + "base16ct", + "der", + "generic-array 0.14.6", + "pkcs8", + "subtle 2.4.1", + "zeroize", +] + +[[package]] +name = "secp256k1" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9512ffd81e3a3503ed401f79c33168b9148c75038956039166cd750eaa037c3" +dependencies = [ + "bitcoin_hashes 0.11.0", + "secp256k1-sys", + "serde", +] + +[[package]] +name = "secp256k1-sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83080e2c2fc1006e625be82e5d1eb6a43b7fd9578b617fcc55814daf286bba4b" +dependencies = [ + "cc", +] + +[[package]] +name = "security-framework" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "segment" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bdcc286fff0e7c5ccd46c06a301c7a8a848b06acedc6983707bd311eb358002" +dependencies = [ + "async-trait", + "chrono", + "reqwest", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser 0.7.0", +] + +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser 0.10.2", +] + +[[package]] +name = "semver" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4" + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + +[[package]] +name = "serde" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "256b9932320c590e707b94576e3cc1f7c9024d0ee6612dfbcf1cb106cbe8e055" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde-redis" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78a6774398484da90606c597852a9662188a3611c912ed6eb29fc81812605c0d" +dependencies = [ + "redis", + "serde", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b4c031cd0d9014307d82b8abf653c0290fbdaeb4c02d00c63cf52f728628bf" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde_bytes" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc50e8183eeeb6178dcb167ae34a8051d63535023ae38b5d8d12beae193d37b" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_cbor" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" +dependencies = [ + "half", + "serde", +] + +[[package]] +name = "serde_derive" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4eae9b04cbffdfd550eb462ed33bc6a1b68c935127d008b27444d08380f94e4" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "serde_derive_internals" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "serde_json" +version = "1.0.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db" +dependencies = [ + "indexmap", + "itoa 1.0.4", + "ryu", + "serde", +] + +[[package]] +name = "serde_repr" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe39d9fbb0ebf5eb2c7cb7e2a47e4f462fad1379f1166b8ae49ad9eae89a7ca" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "serde_stacker" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037227ef03e9c319736423e8d2e29d8695315094b473030cdca306af3ad52688" +dependencies = [ + "serde", + "stacker", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa 1.0.4", + "ryu", + "serde", +] + +[[package]] +name = "serde_v8" +version = "0.57.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3c3efa9cff97d5a543df0508c37af619e422fb92eb525f38d255d46df7a0eb7" +dependencies = [ + "bytes", + "derive_more", + "serde", + "serde_bytes", + "smallvec", + "v8", +] + +[[package]] +name = "serde_with" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" +dependencies = [ + "serde", + "serde_with_macros", +] + +[[package]] +name = "serde_with_macros" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" +dependencies = [ + "darling", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "serde_yaml" +version = "0.8.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578a7433b776b56a35785ed5ce9a7e777ac0598aac5a6dd1b4b18a307c7fc71b" +dependencies = [ + "indexmap", + "ryu", + "serde", + "yaml-rust", +] + +[[package]] +name = "sha-1" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + +[[package]] +name = "sha-1" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.6", +] + +[[package]] +name = "sha1" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" +dependencies = [ + "sha1_smol", +] + +[[package]] +name = "sha1_smol" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" + +[[package]] +name = "sha2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" +dependencies = [ + "block-buffer 0.7.3", + "digest 0.8.1", + "fake-simd", + "opaque-debug 0.2.3", +] + +[[package]] +name = "sha2" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + +[[package]] +name = "sha2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.6", +] + +[[package]] +name = "sha2-asm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c2f225be6502f2134e6bbb35bb5e2957e41ffa0495ed08bce2e2b4ca885da4" +dependencies = [ + "cc", +] + +[[package]] +name = "sha3" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd26bc0e7a2e3a7c959bc494caf58b72ee0c71d67704e9520f736ca7e4853ecf" +dependencies = [ + "block-buffer 0.7.3", + "byte-tools", + "digest 0.8.1", + "keccak", + "opaque-debug 0.2.3", +] + +[[package]] +name = "sha3" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f81199417d4e5de3f04b1e871023acea7389672c4135918f05aa9cbf2f2fa809" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "keccak", + "opaque-debug 0.3.0", +] + +[[package]] +name = "sha3" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdf0c33fae925bdc080598b84bc15c55e7b9a4a43b3c704da051f977469691c9" +dependencies = [ + "digest 0.10.6", + "keccak", +] + +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shell-escape" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f" + +[[package]] +name = "signal-hook" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a253b5e89e2698464fc26b545c9edceb338e18a89effeeecfea192c3025be29d" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-mio" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" +dependencies = [ + "libc", + "mio 0.7.14", + "mio 0.8.5", + "signal-hook", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" +dependencies = [ + "libc", +] + +[[package]] +name = "signature" +version = "1.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c" +dependencies = [ + "digest 0.10.6", + "rand_core 0.6.4", +] + +[[package]] +name = "simd-abstraction" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2880f3f7b392823ee65bbcc681961cd8e698c6a30e91ab9b4eef1f9c6c226d8" + +[[package]] +name = "similar" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420acb44afdae038210c99e69aae24109f32f15500aa708e81d46c9f29d55fcf" + +[[package]] +name = "siphasher" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" + +[[package]] +name = "slab" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" +dependencies = [ + "autocfg 1.1.0", +] + +[[package]] +name = "slog" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8347046d4ebd943127157b94d63abb990fcf729dc4e9978927fdf4ac3c998d06" + +[[package]] +name = "slog-async" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "766c59b252e62a34651412870ff55d8c4e6d04df19b43eecb2703e417b097ffe" +dependencies = [ + "crossbeam-channel", + "slog", + "take_mut", + "thread_local", +] + +[[package]] +name = "slog-atomic" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b517f2dda9e1458733eb8350bad1a3632ffed8141be4c0f3d6def899a9b066" +dependencies = [ + "arc-swap", + "slog", +] + +[[package]] +name = "slog-json" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e1e53f61af1e3c8b852eef0a9dee29008f55d6dd63794f3f12cef786cf0f219" +dependencies = [ + "serde", + "serde_json", + "slog", + "time 0.3.17", +] + +[[package]] +name = "slog-scope" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f95a4b4c3274cd2869549da82b57ccc930859bdbf5bcea0424bc5f140b3c786" +dependencies = [ + "arc-swap", + "lazy_static", + "slog", +] + +[[package]] +name = "slog-term" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87d29185c55b7b258b4f120eab00f48557d4d9bc814f41713f449d35b0f8977c" +dependencies = [ + "atty", + "slog", + "term 0.7.0", + "thread_local", + "time 0.3.17", +] + +[[package]] +name = "smallvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + +[[package]] +name = "socket2" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "sourcemap" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e031f2463ecbdd5f34c950f89f5c1e1032f22c0f8e3dc4bdb2e8b6658cf61eb" +dependencies = [ + "base64 0.11.0", + "if_chain", + "lazy_static", + "regex", + "rustc_version 0.2.3", + "serde", + "serde_json", + "url", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "spin" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6002a767bff9e83f8eeecf883ecb8011875a21ae8da43bffb817a57e78cc09" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable-pattern" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4564168c00635f88eaed410d5efa8131afa8d8699a612c80c455a0ba05c21045" +dependencies = [ + "memchr", +] + +[[package]] +name = "stacker" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c886bd4480155fd3ef527d45e9ac8dd7118a898a46530b7b94c3e21866259fce" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "winapi", +] + +[[package]] +name = "stacks-common" +version = "0.0.1" +source = "git+https://github.com/stacks-network/stacks-blockchain.git?rev=eedba787a36d68213501337ba50d1856f41b869a#eedba787a36d68213501337ba50d1856f41b869a" +dependencies = [ + "chrono", + "curve25519-dalek", + "ed25519-dalek", + "lazy_static", + "libc", + "libsecp256k1 0.5.0", + "percent-encoding", + "rand 0.7.3", + "ripemd", + "rusqlite", + "secp256k1", + "serde", + "serde_derive", + "serde_json", + "sha2 0.10.6", + "sha3 0.10.6", + "time 0.2.27", +] + +[[package]] +name = "stacks-devnet-js" +version = "1.4.0" +dependencies = [ + "chainhook-types", + "clarinet-deployments", + "clarinet-files", + "clarinet-utils", + "crossbeam-channel", + "error-chain 0.12.4", + "hiro-system-kit", + "neon", + "num", + "serde", + "stacks-network", +] + +[[package]] +name = "stacks-network" +version = "1.4.0" +dependencies = [ + "base58 0.2.0", + "bitcoin", + "bitcoincore-rpc", + "bollard", + "chainhook-event-observer", + "chainhook-types", + "chrono", + "clarinet-deployments", + "clarinet-files", + "clarinet-utils", + "clarity-repl", + "crossbeam-channel", + "crossterm 0.22.1", + "ctrlc", + "dirs 4.0.0", + "futures", + "hiro-system-kit", + "reqwest", + "serde", + "serde_derive", + "serde_json", + "stacks-rpc-client", + "tracing", + "tracing-appender", + "tracing-subscriber", + "tui", +] + +[[package]] +name = "stacks-rpc-client" +version = "1.0.0" +dependencies = [ + "clarinet-utils", + "clarity-repl", + "reqwest", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "standback" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" +dependencies = [ + "version_check", +] + +[[package]] +name = "state" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbe866e1e51e8260c9eed836a042a5e7f6726bb2b411dffeaa712e19c388f23b" +dependencies = [ + "loom", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "stdweb" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" +dependencies = [ + "discard", + "rustc_version 0.2.3", + "stdweb-derive", + "stdweb-internal-macros", + "stdweb-internal-runtime", + "wasm-bindgen", +] + +[[package]] +name = "stdweb-derive" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "serde", + "serde_derive", + "syn 1.0.105", +] + +[[package]] +name = "stdweb-internal-macros" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" +dependencies = [ + "base-x", + "proc-macro2 1.0.47", + "quote 1.0.21", + "serde", + "serde_derive", + "serde_json", + "sha1", + "syn 1.0.105", +] + +[[package]] +name = "stdweb-internal-runtime" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" + +[[package]] +name = "str-buf" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e08d8363704e6c71fc928674353e6b7c23dcea9d82d7012c8faf2a3a025f8d0" + +[[package]] +name = "string_cache" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213494b7a2b503146286049378ce02b482200519accc31872ee8be91fa820a08" +dependencies = [ + "new_debug_unreachable", + "once_cell", + "parking_lot 0.12.1", + "phf_shared", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2 1.0.47", + "quote 1.0.21", +] + +[[package]] +name = "string_enum" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "994453cd270ad0265796eb24abf5540091ed03e681c5f3c12bc33e4db33253e1" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "strum" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae14b91c7d11c9a851d3fbc80a963198998c2a64eec840477fa92d8ce9b70bb" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38" +dependencies = [ + "heck 0.3.3", + "proc-macro2 1.0.47", + "quote 1.0.21", + "rustversion", + "syn 1.0.105", +] + +[[package]] +name = "subtle" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee" + +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + +[[package]] +name = "swc_atoms" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d99c0ac33707dd1162a3665d6ca1a28b2f6594e9c37c4703e417fc5e1ce532e" +dependencies = [ + "once_cell", + "rustc-hash", + "serde", + "string_cache", + "string_cache_codegen", +] + +[[package]] +name = "swc_bundler" +version = "0.169.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fd675a730040ce147232e7021aebebfbe16098079824763578cd6b597632ccc" +dependencies = [ + "ahash", + "anyhow", + "crc", + "indexmap", + "is-macro", + "once_cell", + "parking_lot 0.12.1", + "petgraph", + "radix_fmt", + "relative-path", + "retain_mut", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_codegen", + "swc_ecma_loader", + "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_optimization", + "swc_ecma_utils", + "swc_ecma_visit", + "swc_fast_graph", + "swc_graph_analyzer", + "tracing", +] + +[[package]] +name = "swc_common" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68e76a324fa0d7240e790c78914f39fdecfa9d87ef4efed591124b58607a4a4a" +dependencies = [ + "ahash", + "ast_node", + "better_scoped_tls", + "cfg-if", + "debug_unreachable", + "either", + "from_variant", + "num-bigint", + "once_cell", + "rustc-hash", + "serde", + "siphasher", + "sourcemap", + "string_cache", + "swc_atoms", + "swc_eq_ignore_macros", + "swc_visit", + "tracing", + "unicode-width", + "url", +] + +[[package]] +name = "swc_config" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4de36224eb9498fccd4e68971f0b83326ccf8592c2d424f257f3a1c76b2b211" +dependencies = [ + "indexmap", + "serde", + "serde_json", + "swc_config_macro", +] + +[[package]] +name = "swc_config_macro" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb64bc03d90fd5c90d6ab917bb2b1d7fbd31957df39e31ea24a3f554b4372251" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "swc_ecma_ast" +version = "0.84.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cce1fb31e3a100feb31f94647fe27e457bc13b17a8931204fdc9bc58a15c936a" +dependencies = [ + "bitflags", + "is-macro", + "num-bigint", + "scoped-tls", + "serde", + "string_enum", + "swc_atoms", + "swc_common", + "unicode-id", +] + +[[package]] +name = "swc_ecma_codegen" +version = "0.115.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d09abf1639f76d3d174225fdb608805f9c21d4c455f4dd2ef6ab156701f1f82a" +dependencies = [ + "memchr", + "num-bigint", + "once_cell", + "rustc-hash", + "sourcemap", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_codegen_macros", + "tracing", +] + +[[package]] +name = "swc_ecma_codegen_macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0159c99f81f52e48fe692ef7af1b0990b45d3006b14c6629be0b1ffee1b23aea" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "swc_ecma_dep_graph" +version = "0.83.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "832d9690a915f50c6dd86d107c9c9ec37b3d8dab59ed45814ba7bc63e0aa5a87" +dependencies = [ + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_loader" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710c86eb2b253160d4a02fa77057f1c493b3932d1b83430cbbc1e7823eb47e8c" +dependencies = [ + "ahash", + "anyhow", + "pathdiff", + "serde", + "swc_common", + "tracing", +] + +[[package]] +name = "swc_ecma_parser" +version = "0.111.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc1766e5b969c59e51a5dfe9337755d7380a891e579dd6b0eb7816587c7ea7aa" +dependencies = [ + "either", + "enum_kind", + "lexical", + "num-bigint", + "serde", + "smallvec", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "tracing", + "typed-arena", +] + +[[package]] +name = "swc_ecma_transforms_base" +version = "0.97.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b316a99dde0ef85f1878aaa9f4bf9b15f16e999c56ed31a1433928c754ae4e" +dependencies = [ + "better_scoped_tls", + "bitflags", + "num_cpus", + "once_cell", + "phf", + "rustc-hash", + "serde", + "smallvec", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "swc_ecma_utils", + "swc_ecma_visit", + "tracing", +] + +[[package]] +name = "swc_ecma_transforms_classes" +version = "0.85.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c853c4366e81092d38b746e71adffc1150c694f02c1068c9fa24abbdc373a65f" +dependencies = [ + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_transforms_base", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_transforms_macros" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebf907935ec5492256b523ae7935a824d9fdc0368dcadc41375bad0dca91cd8b" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "swc_ecma_transforms_optimization" +version = "0.144.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9413ed145b0c3e693d18760a72c72bb7ac3e522edbb88bfe0c6c161a7b148281" +dependencies = [ + "ahash", + "dashmap", + "indexmap", + "once_cell", + "rustc-hash", + "serde_json", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_macros", + "swc_ecma_utils", + "swc_ecma_visit", + "tracing", +] + +[[package]] +name = "swc_ecma_transforms_proposal" +version = "0.122.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ebc6e03a51f9adcbc40ec144c9bbe78de872bf6f8f581f3abd51187ec6e648" +dependencies = [ + "either", + "serde", + "smallvec", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_transforms_base", + "swc_ecma_transforms_classes", + "swc_ecma_transforms_macros", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_transforms_react" +version = "0.133.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6b0516e231008722175bc0841bf4f3fdcfd3276ca0bf4878d6e87af5c50f324" +dependencies = [ + "ahash", + "base64 0.13.1", + "dashmap", + "indexmap", + "once_cell", + "regex", + "serde", + "sha-1 0.10.1", + "string_enum", + "swc_atoms", + "swc_common", + "swc_config", + "swc_ecma_ast", + "swc_ecma_parser", + "swc_ecma_transforms_base", + "swc_ecma_transforms_macros", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_transforms_typescript" +version = "0.137.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6716a73401b5d717d6fd20159385ce09adbdd3afc765c3890859d84ada8af729" +dependencies = [ + "serde", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_transforms_base", + "swc_ecma_transforms_react", + "swc_ecma_utils", + "swc_ecma_visit", +] + +[[package]] +name = "swc_ecma_utils" +version = "0.93.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70981d5ef10c0ff0a002e21decbca9dde5b40c2fc0d0bc6eaebb219a8e0a5f7d" +dependencies = [ + "indexmap", + "once_cell", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_ecma_visit", + "tracing", + "unicode-id", +] + +[[package]] +name = "swc_ecma_visit" +version = "0.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcd081250d664808fcd23110202728811236c87f527656ffc1db7f00ac1a06dd" +dependencies = [ + "num-bigint", + "swc_atoms", + "swc_common", + "swc_ecma_ast", + "swc_visit", + "tracing", +] + +[[package]] +name = "swc_eq_ignore_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c20468634668c2bbab581947bb8c75c97158d5a6959f4ba33df20983b20b4f6" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "swc_fast_graph" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9260826bb82481fb946ca653d10196f2653beba1b566b72f42ba7046e4ad0c8f" +dependencies = [ + "ahash", + "indexmap", + "petgraph", + "swc_common", +] + +[[package]] +name = "swc_graph_analyzer" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9b192a3b556cf0a81b4dcb8fa35374d306cd46f806dce937599b40e2d945e51" +dependencies = [ + "ahash", + "auto_impl", + "petgraph", + "swc_fast_graph", + "tracing", +] + +[[package]] +name = "swc_macros_common" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4be988307882648d9bc7c71a6a73322b7520ef0211e920489a98f8391d8caa2" +dependencies = [ + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "swc_visit" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fafa6c946bdbe601f5511140776d59e82a03f52a5e5039192b4b96f3ca639d88" +dependencies = [ + "either", + "swc_visit_macros", +] + +[[package]] +name = "swc_visit_macros" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad1b8e0b2d48660bc454f70495e9bb583f9bf501f28165568569946e62f44a2" +dependencies = [ + "Inflector", + "pmutil", + "proc-macro2 1.0.47", + "quote 1.0.21", + "swc_macros_common", + "syn 1.0.105", +] + +[[package]] +name = "syn" +version = "0.15.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" +dependencies = [ + "proc-macro2 0.4.30", + "quote 0.6.13", + "unicode-xid 0.1.0", +] + +[[package]] +name = "syn" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b9b43d45702de4c839cb9b51d9f529c5dd26a4aff255b42b1ebc03e88ee908" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "unicode-ident", +] + +[[package]] +name = "sys-info" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b3a0d0aba8bf96a0e1ddfdc352fc53b3df7f39318c71854910c3c4b024ae52c" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "take_mut" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" + +[[package]] +name = "tar" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b55807c0344e1e6c04d7c965f5289c39a8d94ae23ed5c0b57aabac549f871c6" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "tempfile" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" +dependencies = [ + "cfg-if", + "fastrand", + "libc", + "redox_syscall 0.2.16", + "remove_dir_all", + "winapi", +] + +[[package]] +name = "term" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd106a334b7657c10b7c540a0106114feadeb4dc314513e97df481d5d966f42" +dependencies = [ + "byteorder", + "dirs 1.0.5", + "winapi", +] + +[[package]] +name = "term" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f" +dependencies = [ + "dirs-next", + "rustversion", + "winapi", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "text-size" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "288cb548dbe72b652243ea797201f3d481a0609a967980fcc5b2315ea811560a" + +[[package]] +name = "text_lines" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49e3c53dd04de8b8e8390bc4fab57f6db7af7d33b086fe411803e6351c9f9f9" +dependencies = [ + "serde", +] + +[[package]] +name = "text_lines" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd5828de7deaa782e1dd713006ae96b3bee32d3279b79eb67ecf8072c059bcf" + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "textwrap" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" + +[[package]] +name = "thiserror" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "thread_local" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" +dependencies = [ + "once_cell", +] + +[[package]] +name = "time" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", +] + +[[package]] +name = "time" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" +dependencies = [ + "const_fn", + "libc", + "standback", + "stdweb", + "time-macros 0.1.1", + "version_check", + "winapi", +] + +[[package]] +name = "time" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376" +dependencies = [ + "itoa 1.0.4", + "libc", + "num_threads", + "serde", + "time-core", + "time-macros 0.2.6", +] + +[[package]] +name = "time-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" + +[[package]] +name = "time-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" +dependencies = [ + "proc-macro-hack", + "time-macros-impl", +] + +[[package]] +name = "time-macros" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2" +dependencies = [ + "time-core", +] + +[[package]] +name = "time-macros-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" +dependencies = [ + "proc-macro-hack", + "proc-macro2 1.0.47", + "quote 1.0.21", + "standback", + "syn 1.0.105", +] + +[[package]] +name = "tiny-hderive" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01b874a4992538d4b2f4fbbac11b9419d685f4b39bdc3fed95b04e07bfd76040" +dependencies = [ + "base58 0.1.0", + "hmac 0.7.1", + "libsecp256k1 0.3.5", + "memzero", + "sha2 0.8.2", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + +[[package]] +name = "tokio" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae" +dependencies = [ + "autocfg 1.1.0", + "bytes", + "libc", + "memchr", + "mio 0.8.5", + "num_cpus", + "parking_lot 0.12.1", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.42.0", +] + +[[package]] +name = "tokio-macros" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.23.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" +dependencies = [ + "rustls", + "tokio", + "webpki", +] + +[[package]] +name = "tokio-stream" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d660770404473ccd7bc9f8b28494a811bc18542b915c0855c51e8f419d5223ce" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e80b39df6afcc12cdf752398ade96a6b9e99c903dfdc36e53ad10b9c366bca72" +dependencies = [ + "futures-util", + "log", + "rustls", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki", + "webpki-roots", +] + +[[package]] +name = "tokio-util" +version = "0.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "log", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f988a1a1adc2fb21f9c12aa96441da33a1728193ae0b95d2be22dbd17fcb4e5c" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "toml" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "736b60249cb25337bc196faa43ee12c705e426f3d55c214d73a4e7be06f92cb4" + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "indexmap", + "serde", +] + +[[package]] +name = "tower" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" +dependencies = [ + "futures-core", + "futures-util", + "pin-project", + "pin-project-lite", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" + +[[package]] +name = "tower-lsp" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43e094780b4447366c59f79acfd65b1375ecaa84e61dddbde1421aa506334024" +dependencies = [ + "async-trait", + "auto_impl", + "bytes", + "dashmap", + "futures", + "httparse", + "log", + "lsp-types", + "memchr", + "serde", + "serde_json", + "tokio", + "tokio-util 0.7.2", + "tower", + "tower-lsp-macros", +] + +[[package]] +name = "tower-lsp-macros" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebd99eec668d0a450c177acbc4d05e0d0d13b1f8d3db13cd706c52cbec4ac04" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "tower-service" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" + +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" +dependencies = [ + "crossbeam-channel", + "time 0.3.17", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4017f8f45139870ca7e672686113917c71c7a6e02d4924eda67186083c03081a" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", +] + +[[package]] +name = "tracing-core" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +dependencies = [ + "lazy_static", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "trust-dns-proto" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c31f240f59877c3d4bb3b3ea0ec5a6a0cff07323580ff8c7a605cd7d08b255d" +dependencies = [ + "async-trait", + "cfg-if", + "data-encoding", + "enum-as-inner", + "futures-channel", + "futures-io", + "futures-util", + "idna 0.2.3", + "ipnet", + "lazy_static", + "log", + "rand 0.8.5", + "serde", + "smallvec", + "thiserror", + "tinyvec", + "tokio", + "url", +] + +[[package]] +name = "trust-dns-resolver" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4ba72c2ea84515690c9fcef4c6c660bb9df3036ed1051686de84605b74fd558" +dependencies = [ + "cfg-if", + "futures-util", + "ipconfig", + "lazy_static", + "log", + "lru-cache", + "parking_lot 0.12.1", + "resolv-conf", + "serde", + "smallvec", + "thiserror", + "tokio", + "trust-dns-proto", +] + +[[package]] +name = "try-lock" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" + +[[package]] +name = "tui" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96fe69244ec2af261bced1d9046a6fee6c8c2a6b0228e59e5ba39bc8ba4ed729" +dependencies = [ + "bitflags", + "cassowary", + "crossterm 0.23.2", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "tungstenite" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ad3713a14ae247f22a728a0456a545df14acf3867f905adff84be99e23b3ad1" +dependencies = [ + "base64 0.13.1", + "byteorder", + "bytes", + "http", + "httparse", + "log", + "rand 0.8.5", + "rustls", + "sha-1 0.9.8", + "thiserror", + "url", + "utf-8", + "webpki", +] + +[[package]] +name = "twox-hash" +version = "1.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" +dependencies = [ + "cfg-if", + "rand 0.8.5", + "static_assertions", +] + +[[package]] +name = "typed-arena" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0685c84d5d54d1c26f7d3eb96cd41550adb97baed141a761cf335d3d33bcd0ae" + +[[package]] +name = "typenum" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" + +[[package]] +name = "ubyte" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c81f0dae7d286ad0d9366d7679a77934cfc3cf3a8d67e82669794412b2368fe6" +dependencies = [ + "serde", +] + +[[package]] +name = "ucd-trie" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" + +[[package]] +name = "uncased" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09b01702b0fd0b3fadcf98e098780badda8742d4f4a7676615cad90e8ac73622" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-ucd-ident" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" + +[[package]] +name = "unicode-id" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d70b6494226b36008c8366c288d77190b3fad2eb4c10533139c1c1f461127f1a" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" + +[[package]] +name = "unicode-normalization" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fdbf052a0783de01e944a6ce7a8cb939e295b1e7be835a1112c3b9a7f047a5a" + +[[package]] +name = "unicode-width" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" + +[[package]] +name = "unicode-xid" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" + +[[package]] +name = "universal-hash" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05" +dependencies = [ + "generic-array 0.14.6", + "subtle 2.4.1", +] + +[[package]] +name = "unreachable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2ae5ddb18e1c92664717616dd9549dde73f539f01bd7b77c2edb2446bdff91" +dependencies = [ + "void", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "url" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +dependencies = [ + "form_urlencoded", + "idna 0.3.0", + "percent-encoding", + "serde", +] + +[[package]] +name = "urlpattern" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9bd5ff03aea02fa45b13a7980151fe45009af1980ba69f651ec367121a31609" +dependencies = [ + "derive_more", + "regex", + "serde", + "unic-ucd-ident", + "url", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8parse" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936e4b492acfd135421d8dca4b1aa80a7bfc26e702ef3af710e0752684df5372" + +[[package]] +name = "uuid" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a" +dependencies = [ + "rand 0.6.5", +] + +[[package]] +name = "uuid" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfcd319456c4d6ea10087ed423473267e1a071f3bc0aa89f80d60997843c6f0" +dependencies = [ + "getrandom 0.2.8", + "serde", +] + +[[package]] +name = "v8" +version = "0.47.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be156dece7a023d5959a72dc0d398d6c95100ec601a2cea10d868da143e85166" +dependencies = [ + "bitflags", + "fslock", + "lazy_static", + "libc", + "which", +] + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + +[[package]] +name = "walkdir" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" +dependencies = [ + "same-file", + "winapi", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +dependencies = [ + "log", + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23639446165ca5a5de86ae1d8896b737ae80319560fbaa4c2887b7da6e7ebd7d" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" +dependencies = [ + "quote 1.0.21", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" +dependencies = [ + "proc-macro2 1.0.47", + "quote 1.0.21", + "syn 1.0.105", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" + +[[package]] +name = "web-sys" +version = "0.3.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "webpki-roots" +version = "0.22.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368bfe657969fb01238bb756d351dcade285e0f6fcbd36dcb23359a5169975be" +dependencies = [ + "webpki", +] + +[[package]] +name = "which" +version = "4.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c831fbbee9e129a8cf93e7747a82da9d95ba8e16621cae60ec2cdc849bacb7b" +dependencies = [ + "either", + "libc", + "once_cell", +] + +[[package]] +name = "widestring" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17882f045410753661207383517a6f62ec3dbeb6a4ed2acce01f0728238d1983" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1c4bd0a50ac6020f65184721f758dba47bb9fbc2133df715ec74a237b26794a" +dependencies = [ + "windows_aarch64_msvc 0.39.0", + "windows_i686_gnu 0.39.0", + "windows_i686_msvc 0.39.0", + "windows_x86_64_gnu 0.39.0", + "windows_x86_64_msvc 0.39.0", +] + +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc 0.36.1", + "windows_i686_gnu 0.36.1", + "windows_i686_msvc 0.36.1", + "windows_x86_64_gnu 0.36.1", + "windows_x86_64_msvc 0.36.1", +] + +[[package]] +name = "windows-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc 0.42.0", + "windows_i686_gnu 0.42.0", + "windows_i686_msvc 0.42.0", + "windows_x86_64_gnu 0.42.0", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc 0.42.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7711666096bd4096ffa835238905bb33fb87267910e154b18b44eaabb340f2" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_gnu" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "763fc57100a5f7042e3057e7e8d9bdd7860d330070251a73d003563a3bb49e1b" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_i686_msvc" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7cbfe58828921e10a9f446fcaaf649204dcfe6c1ddd712c5eebae6bda1106" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6868c165637d653ae1e8dc4d82c25d4f97dd6605eaa8d784b5c6e0ab2a252b65" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e4d40883ae9cae962787ca76ba76390ffa29214667a111db9e0a1ad8377e809" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + +[[package]] +name = "winres" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b68db261ef59e9e52806f688020631e987592bd83619edccda9c47d42cde4f6c" +dependencies = [ + "toml 0.5.9", +] + +[[package]] +name = "xattr" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d1526bbe5aaeb5eb06885f4d987bcdfa5e23187055de9b83fe00156a821fabc" +dependencies = [ + "libc", +] + +[[package]] +name = "yaml-rust" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" +dependencies = [ + "linked-hash-map", +] + +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" + +[[package]] +name = "zeroize" +version = "1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f" + +[[package]] +name = "zmq" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aad98a7a617d608cd9e1127147f630d24af07c7cd95ba1533246d96cbdd76c66" +dependencies = [ + "bitflags", + "libc", + "log", + "zmq-sys", +] + +[[package]] +name = "zmq-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d33a2c51dde24d5b451a2ed4b488266df221a5eaee2ee519933dc46b9a9b3648" +dependencies = [ + "libc", + "metadeps", +] + +[[package]] +name = "zstd" +version = "0.11.1+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a16b8414fde0414e90c612eba70985577451c4c504b99885ebed24762cb81a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "5.0.1+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c12659121420dd6365c5c3de4901f97145b79651fb1d25814020ed2ed0585ae" +dependencies = [ + "libc", + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.1+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd07cbbc53846d9145dbffdf6dd09a7a0aa52be46741825f5c97bdd4f73f12b" +dependencies = [ + "cc", + "libc", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b5c6e61 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +members = [ + "components/chainhook-event-observer", + "components/chainhook-cli", + "components/chainhook-types-rs", + "components/hiro-system-kit", +] +default-members = ["components/chainhook-cli", "components/chainhook-event-observer"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..30ace6a --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3414046 --- /dev/null +++ b/README.md @@ -0,0 +1,816 @@ +# Clarinet + +Clarinet is a Clarity runtime packaged as a command line tool, designed to facilitate smart contract understanding, +development, testing and deployment. Clarinet consists of a Clarity Read-Evaluate-Print-Loop (REPL) environment and a testing harness. When used together, Clarity and the REPL environment enable you to rapidly develop and test a Clarity smart contract, allowing you to deploy the contract to a: + +- devnet - a local standalone development environment that simulates Bitcoin, Stacks node and other helpful components, similar to a staging environment. +- [testnet](https://docs.stacks.co/docs/understand-stacks/testnet) - a testing environment not running in production. +- [mainnet](https://stacks.org/stacks2mainnet) - a production environment where you can deploy smart contracts. + +Clarity is a **decidable** smart contract language that optimizes for predictability and security, meaning you can know with certainty, from the code itself, what the program will do. Smart contracts allow you to encode essential business logic on a blockchain. + +![screenshot](docs/images/demo.gif) + +### Clarinet 101 + +Hiro has created an introductory video tutorial series that guides you through some of the fundamentals of Clarinet, and how it can help develop, test, and deploy Clarity smart contracts. + +Please review and watch the YouTube playlist on [Hiro's Youtube](https://www.youtube.com/c/HiroSystems): +[](https://youtube.com/playlist?list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb) channel for information on how to use Clarinet for smart contracts. + +## Installation + +### Install on macOS (Homebrew) + +To install Clarinet on macOS, run the following command: + +```bash +brew install clarinet +``` + +### Install on Windows + +If you would like to install Clarinet on Windows, the easiest way to install Clarinet on Windows is to use the MSI installer. You can download the executable from the [releases page](https://github.com/hirosystems/clarinet/releases). + +Clarinet is also available on Winget; the package manager that Microsoft began including in the latest Windows updates: + +```powershell +winget install clarinet +``` + +### Install from a pre-built binary + +To install Clarinet from pre-built binaries, download the latest release from the [releases page](https://github.com/hirosystems/clarinet/releases). + +Unzip the binary, then copy it to a location that is already in your path, such as `/usr/local/bin`. + +```sh +# note: you can change the v0.27.0 with version that are available in the releases page. +wget -nv https://github.com/hirosystems/clarinet/releases/download/v0.27.0/clarinet-linux-x64-glibc.tar.gz -O clarinet-linux-x64.tar.gz +tar -xf clarinet-linux-x64.tar.gz +chmod +x ./clarinet +mv ./clarinet /usr/local/bin +``` + +On MacOS, you may get security errors when trying to run the pre-compiled binary. You can resolve the security warning +with command + +```sh +xattr -d com.apple.quarantine /path/to/downloaded/clarinet/binary +``` + +### Install from source using Cargo + +If you would like to install Clarinet from source using Cargo, there are some specific steps you will need to follow, which are described below. + +#### Prerequisites + +You must first [Install Rust](https://www.rust-lang.org/tools/install) to use the Rust package manager Cargo. + +If you are using Debian and Ubuntu-based distributions, make sure to run the following command to install required packages before building Clarinet. + +```bash +sudo apt install build-essential pkg-config libssl-dev +``` + +#### Build Clarinet + +When you are ready to build Clarinet, you can build from source using Cargo with the following commands: + +```bash +git clone https://github.com/hirosystems/clarinet.git +cd clarinet +cargo clarinet-install +``` + +By default, you will be in Hiro's development branch, `develop`, with code that has not been released yet. If you plan on submitting any changes to the code, then this is the right branch for you. +If you want the latest stable version, switch to the main branch by entering the following command: + +```bash +git checkout main +``` + +## Getting started with Clarinet + +The following sections describe how to create a new project in Clarinet and populate it with smart contracts. Clarinet +also provides tools for interacting with your contracts in a REPL, and performing automated testing of contracts. + +### Setup shell completions + +Clarinet has many different built-in commands, which are useful to enable tab-completion in your shell. You can use `clarinet` to generate the shell completion scripts for many common shells using the command: + +```sh +clarinet completions (bash|elvish|fish|powershell|zsh) +``` + +After generating the file, please refer to the documentation for your shell to determine where this file should be moved and what other steps may be necessary to enable tab-completion for `clarinet`. + +### Create a new project + +Once you have installed Clarinet, you can create a new project by entering the following command: + +```bash +clarinet new my-project && cd my-project +``` + +Clarinet will create a project directory with the following directory layout: + +```bash +. +├── Clarinet.toml +├── contracts +├── settings +│ └── Devnet.toml +│ └── Testnet.toml +│ └── Mainnet.toml +└── tests +``` + +The `Clarinet.toml` file contains configuration for the smart contracts in your project. When you create contracts in +your project, Clarinet will add them to this file. + +The `settings/Devnet.toml` file contains configuration for accounts in the Clarinet console, including the seed +phrases and initial balances. Initial balances are in microSTX. + +For a detailed video description on how you can create a new project, please see the [Creating a New Project](https://www.youtube.com/watch?v=F_Sb0sNafEg&list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb&index=4) YouTube video. + +### Add a new contract + +Clarinet can handle adding a new contract and its configuration to your project with the following command: + +```bash +$ clarinet contract new bbtc +``` + +Clarinet will add 2 files to your project: the contract file in the `contracts` directory, and the contract test file +in the `tests` directory. + +```bash +. +├── Clarinet.toml +├── contracts +│ └── bbtc.clar +├── settings +│ └── Devnet.toml +│ └── Mainnet.toml +│ └── Testnet.toml +└── tests + └── bbtc_test.ts +``` + +Clarinet will also add configuration to the `Clarinet.toml` file for your contract. + +```toml +[project.cache_location] +path = ".cache" +[contracts.bbtc] +path = "contracts/bbtc.clar" +``` + +You may add contracts to your project by adding the files manually; however, you must add the appropriate configuration +to `Clarinet.toml` in order for Clarinet to recognize the contracts. + +### Check your contracts + +Clarinet provides syntax and semantics checkers for Clarity, which enable you to check if the Clarity code in your project is valid by using the following command: + +```bash +$ clarinet check +``` + +This command uses the `Clarinet.toml` file to locate and analyze all of the contracts in the project. If the Clarity code is valid, the command will indicate success with the following message: + +``` +✔ 2 contracts checked +``` + +The checker may also report warnings that indicate the code is valid; however, you should be aware of a specific condition that might arise. For example, the check-checker analysis discussed below will generate warnings. If there are errors in the code, the output of the command will indicate the kind and location of the errors. + +You may also perform syntax-check on a single file by using the following command. + +```bash +$ clarinet check +``` + +If there are no syntax errors, the output of the command will be a success message similar to the example below. + +``` +✔ Syntax of contract successfully checked +``` + +**Note** Any syntactical errors in the Clarity code will be reported, but type-checking and other semantic checks will not be performed because Clarinet will only look at this one contract, since it does not have the full context to perform a complete check. + +### Static Analysis + +#### Check-Checker + +The check-checker is a static analysis pass you can use to help find potential vulnerabilities in your contracts. To enable this pass, add the following lines to your `Clarinet.toml` file: + +```toml +[repl.analysis] +passes = ["check_checker"] +``` + +The check-checker pass analyzes your contract to identify places where untrusted inputs might be used in a potentially dangerous way. Since public functions can be called by anyone, any arguments passed to these public functions should be considered untrusted. This analysis pass takes the opinion that all untrusted data must be checked before being used to modify the state on the blockchain. Modifying the state includes any operations that affect wallet balances, or any data stored in your contracts. + +- Actions on Stacks wallets: + - stx-burn? + - stx-transfer? +- Actions on fungible tokens: + - ft-burn? + - ft-mint? + - ft-transfer? +- Actions on non-fungible tokens: + - nft-burn? + - nft-mint? + - nft-transfer? +- Actions on persisted data: + - Maps: + - map-delete + - map-insert + - map-set + - Variables: + - var-set + +In addition to those operations, the check-checker is also a bit opinionated and prefers that untrusted data be checked near the source, making the code more readable and maintainable. For this reason, the check-checker also requires that arguments passed into private functions and return values must be checked. + +- Calls to private functions +- Return values + +Finally, another opportunity for exploits appears when contracts call functions from traits. Those traits are untrusted, just like other parameters to public functions, so they are also required to be checked. + +- Dynamic contract calls (through traits) + +When an untrusted input is used in one of these ways, you will see a warning like this: + +``` +bank:27:37: warning: use of potentially unchecked data + (as-contract (stx-transfer? (to-uint amount) tx-sender customer)) + ^~~~~~~~~~~~~~~~ +bank:21:36: note: source of untrusted input here +(define-public (withdrawal-unsafe (amount int)) +``` + +In the case where an operation affects only the sender's own wallet (e.g. calling `stx-transfer?` with the sender set to `tx-sender`), then there is no need to generate a warning, because the untrusted input is only affecting the sender, who is the source of that input. To put it another way, the sender should be able to safely specify parameters in an operation that affects only themselves. This sender is also potentially protected by post-conditions. + +For a more detailed description on how to use the Check-Checker, please see the [Catch Smart Contract Vulnerabilities With Clarinet’s Check-Checker Feature](https://www.youtube.com/watch?v=v2qXFL2owC8&list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb&index=14) YouTube video. + +##### Options + +The check-checker provides some options that can be specified in `Clarinet.toml` to handle common usage scenarios that may reduce false positives from the analysis: + +```toml +[repl.analysis.check_checker] +strict = false +trusted_sender = true +trusted_caller = true +callee_filter = true +``` + +If `strict` is set to true, all other options are ignored and the analysis proceeds with the most strict interpretation of the rules. + +The `trusted_sender` and `trusted_caller` options handle a common practice in smart contracts where there is a concept of a trusted transaction sender (or transaction caller), which is treated like an admin user. Once a check has been performed to validate the sender (or caller), then all inputs should be trusted. + +In the example below, the `asserts!` on line 3 is verifying the `tx-sender`. Because of that check, all inputs are trusted (if the `trusted_sender` option is enabled): + +```clarity +(define-public (take (amount int) (from principal)) + (let ((balance (- (default-to 0 (get amount (map-get? accounts {holder: from}))) amount))) + (asserts! (is-eq tx-sender (var-get bank-owner)) err-unauthorized) + (map-set accounts {holder: from} {amount: balance}) + (stx-transfer? (to-uint amount) (as-contract tx-sender) tx-sender) + ) +) +``` + +The `callee_filter` option loosens the restriction on passing untrusted data to private functions, and instead, allows checks in a called function to propagate up to the caller. This is helpful, because it allows you to define input checks in a function that can be reused. + +In the example below, the private function `validate` checks its parameter. The public function `save` calls `validate`, and when the `callee_filter` option is enabled, that call to `validate` will count as a check for the untrusted input, `amount`, resulting in no warnings from the check-checker. + +```clarity +(define-public (save (amount uint)) + (begin + (try! (validate amount)) + (var-set saved amount) + (ok amount) + ) +) + +(define-private (validate (amount uint)) + (let ((current (var-get saved))) + (asserts! (> amount current) err-too-low) + (asserts! (<= amount (* current u2)) err-too-high) + (ok amount) + ) +) +``` + +##### Annotations + +Sometimes, there is code that the check-checker analysis is unable to determine is safe; however, you know the code is safe. You want to pass this information to the check-checker to disable warnings that you consider to be false positives. To handle these cases, the check-checker supports several annotations, implemented using "magic comments" in the contract code. + +**`#[allow(unchecked_params)]`** + +This annotation tells the check-checker that the associated private function is allowed to receive unchecked arguments. It will not generate a warning for calls to this function that pass unchecked inputs. Inside the private function, the parameters are considered unchecked and could generate warnings. + +```clarity +;; #[allow(unchecked_params)] +(define-private (my-func (amount uint)) + ... +) +``` + +**`#[allow(unchecked_data)]`** + +This annotation tells the check-checker that the following expression is allowed to use unchecked data without warnings. It should be used with care, since this will disable all warnings from the associated expression. + +```clarity +(define-public (dangerous (amount uint)) + (let ((sender tx-sender)) + ;; #[allow(unchecked_data)] + (as-contract (stx-transfer? amount tx-sender sender)) + ) +) +``` + +**`#[filter(var1, var2)]`** + +This annotation tells the check-checker to consider the specified variables to be checked by the following expression. This is useful for the case where your contract does some indirect check that validates that an input is safe, but there is no way for the analysis to recognize this. In place of the list of variable names in the annotation, an `*` may be used to filter all inputs. + +**Note** The command below is the safest and preferred way to silence warnings that you consider false positives. + +```clarity +(define-public (filter_one (amount uint)) + (let ((sender tx-sender)) + ;; #[filter(amount)] + (asserts! (> block-height u1000) (err u400)) + (as-contract (stx-transfer? amount tx-sender sender)) + ) +) +``` + +### Execute a test suite + +Clarinet provides a testing harness based on Deno that can enable you to create automated unit tests or pseudo-integration tests using Typescript. + +```bash +$ clarinet test +``` + +For more information on how to create unit tests using Typescript, see the [Writing Unit Tests Using Typescript](https://www.youtube.com/watch?v=Z4YEHUxHWuE&list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb&index=7) YouTube video. + +When you use the `clarinet contract new foo` command to create a new contract, Clarinet will automatically create a unit test file for this new contract, `tests/foo_test.ts`. Other files under the `tests/_ directory` following the Deno test naming convention will also be included: + +- named test.{ts, tsx, mts, js, mjs, jsx, cjs, cts}, +- or ending with .test.{ts, tsx, mts, js, mjs, jsx, cjs, cts}, +- or ending with \_test.{ts, tsx, mts, js, mjs, jsx, cjs, cts} + +Within these tests, you can simulate mining a block containing transactions using your contract, and then examine the results of those transactions as well as the events generated by them. + +See the [billboard example](examples/billboard/tests/billboard_test.ts) for sample unit tests. + +**Note:** If you see an error in VS Code on the imports in the generated test file(s), that says, "An import path cannot end with a '.ts' extension" (an example is shown below), installing the [Deno extension](https://marketplace.visualstudio.com/items?itemName=denoland.vscode-deno) will resolve this error. + +![VS Code deno error](docs/images/deno-error.png) + +#### Measure and increase code coverage + +To help maximize a smart contract's test coverage, Clarinet can produce a `lcov` report, using the following option: + +```bash +$ clarinet test --coverage +``` + +From there, you can use the `lcov` tooling suite to produce HTML reports: + +```bash +$ brew install lcov +$ genhtml coverage.lcov +$ open index.html +``` + +![lcov](docs/images/lcov.png) + +### Cost optimizations + +Clarinet can also be used to optimize costs. When executing a test suite, Clarinet will keep track of all the costs being computed when executing the `contract-call`, and display the most expensive ones in a table: + +```bash +$ clarinet test --cost +``` + +The `--cost` option can be used in conjunction with `--watch` and filters to maximize productivity, as illustrated here: + +![costs](docs/images/costs.gif) + +### Load contracts in a console + +The Clarinet console is an interactive Clarity REPL environment that runs in-memory. Any contracts in the current project will be +automatically loaded into memory. + +```bash +$ clarinet console +``` + +You can use the `::help` command in the console for a list of valid commands, which can control the state of the +REPL chain, and allow you advance the chain tip. Additionally, you can enter Clarity commands into the console and observe +the result of the command. + +You can exit the console by pressing `Ctrl + C` twice. + +Changes to contracts are not loaded into the console while it is running. If you make any changes to your contracts you +must exit the console and run it again. + +### Spawn a local Devnet + +You can use Clarinet to deploy your contracts to your own local offline environment for testing and +evaluation on a blockchain by using the following command: + +```bash +$ clarinet integrate +``` + +**Note** Make sure you have a working installation of Docker running locally. + +### Interacting with contracts deployed on Mainnet + +Composition and interactions between protocols and contracts are one of the key innovations in blockchains. Clarinet was designed to handle these types of interactions. + +Before referring to contracts deployed on Mainnet, these contracts should be explicitly be listed as a `requirement` in the manifest `Clarinet.toml`, either manually: + +```toml +[project] +name = "my-project" +[[project.requirements]] +contract_id = "SP2KAF9RF86PVX3NEE27DFV1CQX0T4WGR41X3S45C.bitcoin-whales" + +``` + +or with the command: + +```bash +clarinet requirements add SP2KAF9RF86PVX3NEE27DFV1CQX0T4WGR41X3S45C.bitcoin-whales +``` + +Clarinet will be able to resolve the `contract-call?` statements invoking requirements present in your local contracts by downloading and caching a copy of these contracts and using them during the execution of your test suites. All of the different features are available in `clarinet`. + +When deploying your protocol to Devnet / Testnet, for the contracts involving requirements, the setting `remap_requirements` in your deployment plans must be set. + +As a step-by-step example, we use here the following contract, [**bitcoin-whales**](https://explorer.stacks.co/txid/SP2KAF9RF86PVX3NEE27DFV1CQX0T4WGR41X3S45C.bitcoin-whales?chain=mainnet) + +If you examine this contract, you will see that there are 3 different dependencies: two from the **same** +project (included in the same Clarinet.toml file), and one referring to a contract deployed outside of the current project. + +### Same Project + +In the contract snippet shown below *(line:260-265)*, there are dependencies on the contracts conversion and conversion-v2 which are included in the same `Clarinet.toml` file. + +```clarity +(define-read-only (get-token-uri (token-id uint)) + (if (< token-id u5001) + (ok (some (concat (concat (var-get ipfs-root) (unwrap-panic (contract-call? .conversion lookup token-id))) ".json"))) + (ok (some (concat (concat (var-get ipfs-root) (unwrap-panic (contract-call? .conversion-v2 lookup (- token-id u5001)))) ".json"))) + ) +) +``` + +### External Deployer + +In this code snippet, there is a dependency on the `nft-trait` *(line:001)* deployed by `'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9`. + +```clarity +(impl-trait 'SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.nft-trait) +``` + +- Dependencies from **external** contracts should be set in `[[project.requirements]]` + +```toml +[project] +name = "my-project" + +[[project.requirements]] +contract_id = "SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait" + +[project.cache_location] +path = ".cache" + +[contracts.bitcoin-whales] +path = "contracts/bitcoin-whales.clar" + +[contracts.conversion] +path = "contracts/conversion.clar" + +[contracts.conversion-v2] +path = "contracts/conversion-v2.clar" + +[repl.analysis] +passes = ["check_checker"] + +[repl.analysis.check_checker] +strict = false +trusted_sender = false +trusted_caller = false +callee_filter = false +``` + +As a next step we can generate a deployment plan for this project. If you are running `$ clarinet integrate` for the first time, this file should be created by Clarinet. In addition, you can run `$ clarinet deployment generate --devnet` to create or overwrite the file. + +```yaml +--- +id: 0 +name: Devnet deployment +network: devnet +stacks-node: "http://localhost:20443" +bitcoin-node: "http://devnet:devnet@localhost:18443" +plan: + batches: + - id: 0 + transactions: + - requirement-publish: + contract-id: SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait + remap-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM + remap-principals: + SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM + cost: 4680 + path: ".requirements\\SP2PABAF9FTAJYNFZH93XENAJ8FVY99RRM50D2JG9.nft-trait.clar" + - contract-publish: + contract-name: conversion + expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM + cost: 340250 + path: "contracts\\conversion.clar" + anchor-block-only: true + - contract-publish: + contract-name: conversion-v2 + expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM + cost: 351290 + path: "contracts\\conversion-v2.clar" + anchor-block-only: true + - contract-publish: + contract-name: bitcoin-whales + expected-sender: ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM + cost: 87210 + path: "contracts\\bitcoin-whales.clar" + anchor-block-only: true +``` + +As the example above shows, Clarinet will remap the external contract to Hiro's Devnet address. In addition, it will also create a copy of the contract in the folder `requirements` + +### Deploy contracts to Devnet / Testnet / Mainnet + +You can use Clarinet to publish your contracts to Devnet / Testnet / Mainnet environment for testing and evaluation on a blockchain. + +The first step to deploy a contract is to generate a deployment plan, with the following command: + +```bash +$ clarinet deployment generate --mainnet +``` + +After **cautiously** reviewing (and updating if needed) the generated plan, you can use the command to handle the deployments of your contract, according to your deployment plan: + +```bash +$ clarinet deployment apply -p +``` + +### Use Clarinet in your CI workflow as a GitHub Action + +Clarinet may also be used in GitHub Actions as a step of your CI workflows. + +You may set-up a simple workflow by adding the following steps in a file `.github/workflows/github-actions-clarinet.yml`: + +```yaml +name: CI +on: [push] +jobs: + tests: + name: "Test contracts with Clarinet" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: "Execute unit tests" + uses: docker://hirosystems/clarinet:latest + with: + args: test --coverage --manifest-path=./Clarinet.toml + - name: "Export code coverage" + uses: codecov/codecov-action@v1 + with: + files: ./coverage.lcov + verbose: true +``` + +You may also add the steps above in your existing workflows. The generated code coverage output can then be used as is with GitHub Apps like https://codecov.io. + +For more information on how you can use GitHub Actions with Clarinet, please see the [A Simple CI With Clarinet and GitHub](https://www.youtube.com/watch?v=cEv6Mi4EcKQ&list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb&index=8) YouTube video + +### Extensions + +Clarinet can easily be extended by community members: open source contributions to Clarinet are welcome, but you may also write your own Clarinet extensions if you want to integrate Clarity contracts with your own tooling and workflow. + +| Name | wallet access | disk write | disk read | Deployment | Description | +| ------------------------- | ------------- | ---------- | --------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| stacksjs-helper-generator | no | yes | no | https://deno.land/x/clarinet@v1.0.2/ext/stacksjs-helper-generator.ts | Facilitates contract integration by generating some typescript constants that can be used with stacks.js. Never hard code a stacks address again! | +| | | | | | + +#### How to use extensions + +Extensions are run with the following syntax: + +``` +$ clarinet run --allow-write https://deno.land/x/clarinet@v0.29.0/ext/stacksjs-helper-generator.ts +``` + +An extension can be deployed as a standalone plugin on Deno, or may also be a local file if it includes sensitive / private setup informations. + +As illustrated in the example above, permissions (wallet / disk read / disk write) are declared using command flags. If at runtime, the Clarinet extension is trying to write to disk, read disk, or access wallets without permission, the script will fail. + +### Debug your contracts + +#### VS Code Debugger + +Clarinet supports the [Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/) (DAP) which enables you to debug your smart contracts inside of VS Code, or any code editor that supports the DAP protocol. + +To setup a debug session, you will first need to create a `launch.json` file to tell VS Code what you want to debug. The easiest way to do this is to let VS Code generate the template for you by opening the "Run and Debug" view and clicking "create a launch.json file". + +![Run and Debug View](docs/images/run-and-debug.png) + +This will create the file `.vscode/launch.json` with the default template: + +```json +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "clarinet", + "request": "launch", + "name": "Call .foo.bar", + "manifest": "${workspaceFolder}/Clarinet.toml", + "expression": "(contract-call? .foo bar 42)" + } + ] +} +``` + +Depending on your needs, you will want to set the `name` field to whatever makes sense for your project, then set the `expression` to the Clarity expression that you would like to debug. In the case of the default example shown in the template above, the debugger would start executing the `bar` function of the `foo` contract, passing the argument `42`. Once this file is configured, the debugger works as expected for any [VS Code debugging](https://code.visualstudio.com/docs/editor/debugging). + +Execution begins paused at the first expression. The debug toolbar includes buttons to continue, step over, step into, step out, restart, and stop, in that order. + +![debug toolbar](docs/images/debug-toolbar.png) + +Breakpoints can be set by clicking in the left gutter next to the code or using the right-click menu at a specific code location. + +![breakpoint](docs/images/breakpoint.png) + +Data watchpoints may also be set, by clicking the + in the Watch section of the Debug side bar and typing the contract variable to watch in the format `..` or using the shortcut for a local contract, `..`. When a watchpoint is set on a contract variable, execution will pause when its value will change. + +![watchpoint](docs/images/watchpoint.png) + +During execution, the values of the current contract's variables, the current function's arguments, and any local variables (i.e. from a `let` expression) are shown in the side bar. The current watchpoints are also shown with their current values. In both cases, the contents of a map are not shown, but can be queried in the Debug Console. The call stack is also updated to show the call stack of the current execution. + +![view of side bar, showing variables, watchpoints, and call stack](docs/images/sidebar.png) + +At any point during execution, an expression can be evaluated in the current context via the Debug Console. Just type any valid Clarity expression and hit enter to evaluate it. Upon completion, the events emitted and the return value are printed to the debug console. + +![debug console](docs/images/debug-console.png) + +For more information on how you can use VS Code to debug smart contracts, please see the [How to Debug Smart Contracts in Clarinet’s VS Code Extension](https://www.youtube.com/watch?v=DsLCDQSijwk&list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb&index=15) YouTube video. + +#### Command Line Debugger + +Inside of the console (`clarinet console`), there is a debugger for stepping through your contracts on the command line, including support for: + +- Breakpoints + - **Source**: Break at a specific line (and optional column) of a contract (`break` or `b` command) + ``` + b SP466FNC0P7JWTNM2R9T199QRZN1MYEDTAR0KP27.miamicoin-token:28:4 + ``` + - **Function**: Break at a specific function (`break` or `b` command) + ``` + b .crashpunks-v2.transfer + ``` + - **Data**: Break on read/write to a variable or map (`watch` or `w` to break on write, `rwatch` or `rw` to break on read, and `awatch` or `aw` to break on read or write) + ``` + w contracts/SP2KAF9RF86PVX3NEE27DFV1CQX0T4WGR41X3S45C.bitcoin-whales.payout + ``` +- Step execution + - **Step-in**: Step into the sub-expressions (`step` or `s` command) + - **Step-out**: Complete execution of the current expression and return the result back to the parent (`finish` or `f` command) + - **Step-over**: Continue to completion of the current expression, stepping over sub-expressions (`next` or `n` command) + - **Continue**: Continue execution until hitting a breakpoint or completing execution (`continue` or `c` command) +- Evaluate and print the result of any expression (`print` or `p` command) + +To initiate a debug session, first enter the REPL console using the following command: + +``` +clarinet console +``` + +Then, at the REPL prompt, enter this command to debug any expression: + +``` +::debug (contract-call? .foo hello .bar)) +``` + +At the debug prompt, use any of the commands described above, or use `help` to get the full help documentation. + +For more information about how to debug a smart contract using the command line, please see the [Debug Your Smart Contracts With Clarinet’s New Inline Debugger](https://www.youtube.com/watch?v=nVDWeuMnkDs&list=PL5Ujm489LoJaAz9kUJm8lYUWdGJ2AnQTb&index=13) YouTube video. + +#### Execution Trace + +When you are in the console (`clarinet console`), the `::trace ` command enables you to execute an expression and print a trace of the execution, which can be very helpful for identifying problems with the contract. + +This trace shows all function calls, both internal calls to private functions, and contract calls to other contracts. For each call, the parameters and return value are shown in the trace. Any events that are emitted are also shown in the trace. + +![execution trace](docs/images/trace.png) + +### Deploy with Hyperchains on Devnet + +Clarinet can be used for facilitating experimentations with [Hyperchains](https://www.youtube.com/watch?v=PFPwuVCGGuI). +To begin working with subnets, in your `Devnet.toml`, enable the following flag: + +```toml +[devnet] +# ... +enable_subnet_node = true +``` + +This same file may also be used for customizing the subnet-node (miner, etc). + +When running the command: + +```bash +$ clarinet integrate +``` + +Clarinet will spin-up a subnet node. More documentation on how to use and interact with this incoming L2 can be found on the [Hyperchain repository](https://github.com/hirosystems/stacks-subnets). + +## Contributing to Clarinet + +Contributions are welcome and appreciated. The following sections provide information on how you can contribute to Clarinet. + +### Prerequisites + +Before contributing to Clarinet, please ensure you meet the following requirements: + +- rust (>=1.52.0) +- cargo (>=1.52.0) +- node (>=v14.16.0) - Used for git commit hook +- npm (>=7.18.0) - Used for git commit hook + +### Guide + +This repo follows the [Conventional Commit](https://www.conventionalcommits.org/en/v1.0.0/#summary) specification when writing commit messages. + +**Note**It is important that any pull requests you submit have commit messages that follow this standard. + +To start contributing: + +1. Fork this repo and clone the fork locally. +2. Create a new branch + ```bash + git checkout -b + ``` +3. Run `npm i` in the local repo to install and initialize `husky` and `commitlint`. + + ```bash + npm i + ``` + +4. These tools will be used in a `git commit` hook to lint and validate your commit message. If the message is invalid, `commitlint` will alert you to try again and fix it. + + Here is an example of a bad message response: + + ```bash + $ git commit -m "bad message" + $ ⧗ input: bad message + $ ✖ subject may not be empty [subject-empty] + $ ✖ type may not be empty [type-empty] + $ + $ ✖ found 2 problems, 0 warnings + $ ⓘ Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint + $ + $ husky - commit-msg hook exited with code 1 (error) + ``` + + Here is an example of a good message response: + + ```bash + $ git commit -m "fix: added missing dependency" + $ [my-branch 4c028af] fix: added missing dependency + $ 1 file changed, 50 insertions(+) + ``` + +5. After making your changes, ensure the following: + - `cargo build` runs successfully. + - `cargo test` runs successfully. + - You have formatted your code with `cargo fmt --all --` + - All functional tests in the `examples` directory pass. + ```bash + for testdir in $(ls examples); do + pushd examples/${testdir} + ../../target/debug/clarinet test . + popd + done + ``` +6. Submit a pull request against the `develop` branch for review. diff --git a/components/chainhook-cli/Cargo.toml b/components/chainhook-cli/Cargo.toml new file mode 100644 index 0000000..32394d7 --- /dev/null +++ b/components/chainhook-cli/Cargo.toml @@ -0,0 +1,45 @@ +[package] +name = "chainhook-cli" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +csv = "1" +num_cpus = "1.4" +serde = "1" +serde_json = "1" +serde_derive = "1" +redis = "0.21.5" +serde-redis = "0.12.0" +chainhook_event_observer = { package = "chainhook-event-observer", default-features = false, path = "../chainhook-event-observer" } +chainhook_types = { package = "chainhook-types", path = "../chainhook-types-rs" } +hiro_system_kit = { package = "hiro-system-kit", path = "../hiro-system-kit" } +clap = { version = "3.2.23", features = ["derive"], optional = true } +clap_generate = { version = "3.0.3", optional = true } +toml = { version = "0.5.6", features = ["preserve_order"], optional = true } +ctrlc = { version = "3.2.2", optional = true } +reqwest = { version = "0.11", features = ["stream", "json"] } +tokio = { version = "=1.24", features = ["full"] } +futures-util = "0.3.24" +flate2 = "1.0.24" +tar = "0.4.38" +flume = "0.10.14" +ansi_term = "0.12.1" +atty = "0.2.14" +bitcoincore-rpc = "0.16.0" +bitcoincore-rpc-json = "0.16.0" +crossbeam-channel = "0.5.6" + +[dev-dependencies] +criterion = "0.3" +redis = "0.21.5" +clarity_repl = { package = "clarity-repl", path = "../../../clarinet/components/clarity-repl" } +hex = "0.4.3" + +[features] +default = ["cli"] +cli = ["clap", "clap_generate", "toml", "ctrlc", "hiro_system_kit/log"] +debug = ["hiro_system_kit/debug"] +release = ["hiro_system_kit/release"] diff --git a/components/chainhook-cli/Chainhook.toml b/components/chainhook-cli/Chainhook.toml new file mode 100644 index 0000000..3d4db4b --- /dev/null +++ b/components/chainhook-cli/Chainhook.toml @@ -0,0 +1,14 @@ +[storage] +driver = "redis" +redis_uri = "redis://localhost:6379/" + +[chainhooks] +max_stacks_registrations = 500 +max_bitcoin_registrations = 500 + +[network] +mode = "devnet" +bitcoin_node_rpc_url = "http://0.0.0.0:18443" +bitcoin_node_rpc_username = "devnet" +bitcoin_node_rpc_password = "devnet" +stacks_node_rpc_url = "http://0.0.0.0:20443" diff --git a/components/chainhook-cli/README.md b/components/chainhook-cli/README.md new file mode 100644 index 0000000..e1db271 --- /dev/null +++ b/components/chainhook-cli/README.md @@ -0,0 +1,207 @@ +# chainhook-cli + +## Usage + +To get started, [build `clarinet` from source](https://github.com/hirosystems/clarinet#install-from-source-using-cargo), and then `cd components/chainhook-cli` and run `cargo install --path .` to install `chainhook-cli`. + +Before running `chainhook-cli`, you need to [install redis](https://redis.io/docs/getting-started/installation/) and run a redis server locally. + + ### Start a Testnet node + +```bash +$ chainhook-cli start --testnet +``` + +### Start a Mainnet node + +```bash +$ chainhook-cli start --mainnet +``` + +### Start a Devnet node + +```bash +$ chainhook-cli start --devnet +``` + +## Predicates available + +### Bitcoin + +```yaml +# Get any transaction matching a given txid +# `txid` mandatory argument admits: +# - 32 bytes hex encoded type. example: "0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f" +predicate: + txid: 0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f + +# Get any transaction including an OP_RETURN output starting with a set of characters. +# `starts-with` mandatory argument admits: +# - ASCII string type. example: `X2[` +# - hex encoded bytes. example: `0x589403` +predicate: + scope: outputs + op-return: + starts-with: X2[ + +# Get any transaction including an OP_RETURN output matching the sequence of bytes specified +# `equals` mandatory argument admits: +# - hex encoded bytes. example: `0x589403` +predicate: + scope: outputs + op-return: + equals: 0x69bd04208265aca9424d0337dac7d9e84371a2c91ece1891d67d3554bd9fdbe60afc6924d4b0773d90000006700010000006600012 + +# Get any transaction including an OP_RETURN output ending with a set of characters +# `ends-with` mandatory argument admits: +# - ASCII string type. example: `X2[` +# - hex encoded bytes. example: `0x589403` +predicate: + scope: outputs + op-return: + ends-with: 0x76a914000000000000000000000000000000000000000088ac + +# Get any transaction including a Stacks Proof of Burn commitment +predicate: + scope: outputs + stacks-op: + type: pob-commit + +# Get any transaction including a Stacks Proof of Transfer commitment +# `recipients` mandatory argument admits: +# - string "*" +# - array of strings type. example: ["mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC", "muYdXKmX9bByAueDe6KFfHd5Ff1gdN9ErG"] +# - array of hex encoded bytes type. example: ["76a914000000000000000000000000000000000000000088ac", "0x76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac"] +predicate: + scope: outputs + stacks-op: + type: pox-commit + recipients: * + +# Get any transaction including a key registration operation +predicate: + scope: outputs + stacks-op: + type: key-registration + +# Get any transaction including a STX transfer operation +# `recipient` optional argument admits: +# - string encoding a valid STX address. example: "ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG" +# `sender` optional argument admits: +# - string type. example: "mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC" +# - hex encoded bytes type. example: "0x76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" +predicate: + scope: outputs + stacks-op: + type: stx-transfer + +# Get any transaction including a STX lock operation +# `sender` optional argument admits: +# - string type. example: "mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC" +# - hex encoded bytes type. example: "0x76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" +predicate: + scope: outputs + stacks-op: + type: stx-lock + +# Get any transaction including a p2pkh output paying a given recipient +# `p2pkh` construct admits: +# - string type. example: "mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC" +# - hex encoded bytes type. example: "0x76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" +predicate: + scope: outputs + p2pkh: mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC + +# Get any transaction including a p2sh output paying a given recipient +# `p2sh` construct admits: +# - string type. example: "2MxDJ723HBJtEMa2a9vcsns4qztxBuC8Zb2" +# - hex encoded bytes type. example: "0x76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" +predicate: + scope: outputs + p2sh: 2MxDJ723HBJtEMa2a9vcsns4qztxBuC8Zb2 + +# Get any transaction including a p2wpkh output paying a given recipient +# `p2wpkh` construct admits: +# - string type. example: "bcrt1qnxknq3wqtphv7sfwy07m7e4sr6ut9yt6ed99jg" +predicate: + scope: outputs + p2wpkh: bcrt1qnxknq3wqtphv7sfwy07m7e4sr6ut9yt6ed99jg + +# Get any transaction including a p2wsh output paying a given recipient +# `p2wsh` construct admits: +# - string type. example: "bc1qklpmx03a8qkv263gy8te36w0z9yafxplc5kwzc" +predicate: + scope: outputs + p2wsh: bc1qklpmx03a8qkv263gy8te36w0z9yafxplc5kwzc + +# Additional predicates including support for taproot coming soon +``` + +### Stacks + +```yaml +# Get any transaction matching a given txid +# `txid` mandatory argument admits: +# - 32 bytes hex encoded type. example: "0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f" +predicate: + txid: 0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f + +# Get any transaction related to a given fungible token asset identifier +# `asset-identifier` mandatory argument admits: +# - string type, fully qualifying the asset identifier to observe. example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.cbtc-sip10::cbtc` +# `actions` mandatory argument admits: +# - array of string type constrained to `mint`, `transfer` and `burn` values. example: ["mint", "burn"] +predicate: + ft-event: + asset-identifier: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.cbtc-sip10::cbtc' + actions: + - mint + - burn + +# Get any transaction related to a given non fungible token asset identifier +# `asset-identifier` mandatory argument admits: +# - string type, fully qualifying the asset identifier to observe. example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09::monkeys` +# `actions` mandatory argument admits: +# - array of string type constrained to `mint`, `transfer` and `burn` values. example: ["mint", "burn"] +predicate: + nft-event: + asset-identifier: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09::monkeys' + actions: + - transfer + - burn + +# Get any transaction moving STX tokens +# `actions` mandatory argument admits: +# - array of string type constrained to `mint`, `transfer` and `lock` values. example: ["mint", "lock"] +predicate: + stx-event: + actions: + - mint + - lock + +# Get any transaction emitting given print events predicate +# `contract-identifier` mandatory argument admits: +# - string type, fully qualifying the contract to observe. example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09` +# `contains` mandatory argument admits: +# - string type, used for matching event +predicate: + print-event: + contract-identifier: 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.monkey-sip09' + contains: "vault" + +# Get any transaction including a contract deployment +# `deployer` mandatory argument admits: +# - string "*" +# - string encoding a valid STX address. example: "ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG" +predicate: + contract-deploy: + deployer: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM" + +# Get any transaction including a contract deployment implementing a given trait (coming soon) +# `impl-trait` mandatory argument admits: +# - string type, fully qualifying the trait's shape to observe. example: `ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sip09-protocol` +predicate: + contract-deploy: + impl-trait: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM.sip09-protocol" +``` + diff --git a/components/chainhook-cli/benches/codec/clarity.rs b/components/chainhook-cli/benches/codec/clarity.rs new file mode 100644 index 0000000..95c6918 --- /dev/null +++ b/components/chainhook-cli/benches/codec/clarity.rs @@ -0,0 +1,28 @@ +use clarity_repl::clarity::codec::StacksString; +use clarity_repl::clarity::util::hash::{hex_bytes, to_hex}; +use clarity_repl::clarity::ClarityName; +use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use hex::{decode, encode}; + +#[inline] +fn canonical_is_clarity_variable() { + let function_name = ClarityName::try_from("my-method-name").unwrap(); + StacksString::from(function_name.clone()).is_clarity_variable(); +} + +#[inline] +fn proposed_is_clarity_variable() { + let function_name = ClarityName::try_from("my-method-name").unwrap(); +} + +pub fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("canonical_is_clarity_variable ", |b| { + b.iter(|| canonical_is_clarity_variable()) + }); + c.bench_function("proposed_is_clarity_variable ", |b| { + b.iter(|| proposed_is_clarity_variable()) + }); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/components/chainhook-cli/benches/codec/hex.rs b/components/chainhook-cli/benches/codec/hex.rs new file mode 100644 index 0000000..9e1dac6 --- /dev/null +++ b/components/chainhook-cli/benches/codec/hex.rs @@ -0,0 +1,398 @@ +use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use clarity_repl::clarity::util::hash::{hex_bytes, to_hex}; +use hex::{decode, encode}; + +#[inline] +fn decode_hex_str_stacks(input: &str) -> Vec { + hex_bytes(input).unwrap() +} + +#[inline] +fn encode_hex_str_stacks() -> String { + to_hex(&[ + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x04, + 0x00, + 0xa4, + 0x68, + 0xe7, + 0x2d, + 0xf6, + 0x75, + 0x43, + 0x87, + 0x20, + 0x98, + 0x27, + 0x32, + 0x7b, + 0x98, + 0x9f, + 0x4a, + 0x99, + 0x54, + 0x2a, + 0x69, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x77, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xb4, + 0x00, + 0x01, + 0x23, + 0x1c, + 0x21, + 0x39, + 0x49, + 0x45, + 0x53, + 0x17, + 0xd1, + 0x5f, + 0xf2, + 0x5d, + 0xfd, + 0x7a, + 0xd9, + 0xbc, + 0x04, + 0x26, + 0xcf, + 0xfa, + 0x5c, + 0x6f, + 0x5b, + 0xe4, + 0x6e, + 0x79, + 0xfa, + 0x1e, + 0x18, + 0x2b, + 0x61, + 0x45, + 0x18, + 0x0c, + 0x1c, + 0x13, + 0x5d, + 0x6c, + 0xcc, + 0xfc, + 0xc4, + 0x9e, + 0x85, + 0xcb, + 0x82, + 0x5e, + 0x61, + 0x52, + 0x28, + 0xda, + 0xf2, + 0xd1, + 0x66, + 0x3e, + 0x49, + 0xd7, + 0x0c, + 0xd5, + 0xd0, + 0xe1, + 0x96, + 0xd1, + 0x26, + 0xc0, + 0x03, + 0x02, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x05, + 0x16, + 0x7b, + 0x2d, + 0xd1, + 0xf0, + 0xd4, + 0x7f, + 0x59, + 0x67, + 0x21, + 0xc2, + 0x33, + 0xfd, + 0x9b, + 0x2e, + 0x99, + 0x19, + 0xac, + 0x91, + 0x28, + 0x8a, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x1b, + 0x5e, + 0x48, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 + ]) +} + + +#[inline] +fn decode_hex_str_crate(input: &str) -> Vec { + decode(input).unwrap() +} + +#[inline] +fn encode_hex_str_crate() -> String { + encode(&[ + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, + 0x04, + 0x00, + 0xa4, + 0x68, + 0xe7, + 0x2d, + 0xf6, + 0x75, + 0x43, + 0x87, + 0x20, + 0x98, + 0x27, + 0x32, + 0x7b, + 0x98, + 0x9f, + 0x4a, + 0x99, + 0x54, + 0x2a, + 0x69, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x77, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xb4, + 0x00, + 0x01, + 0x23, + 0x1c, + 0x21, + 0x39, + 0x49, + 0x45, + 0x53, + 0x17, + 0xd1, + 0x5f, + 0xf2, + 0x5d, + 0xfd, + 0x7a, + 0xd9, + 0xbc, + 0x04, + 0x26, + 0xcf, + 0xfa, + 0x5c, + 0x6f, + 0x5b, + 0xe4, + 0x6e, + 0x79, + 0xfa, + 0x1e, + 0x18, + 0x2b, + 0x61, + 0x45, + 0x18, + 0x0c, + 0x1c, + 0x13, + 0x5d, + 0x6c, + 0xcc, + 0xfc, + 0xc4, + 0x9e, + 0x85, + 0xcb, + 0x82, + 0x5e, + 0x61, + 0x52, + 0x28, + 0xda, + 0xf2, + 0xd1, + 0x66, + 0x3e, + 0x49, + 0xd7, + 0x0c, + 0xd5, + 0xd0, + 0xe1, + 0x96, + 0xd1, + 0x26, + 0xc0, + 0x03, + 0x02, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x05, + 0x16, + 0x7b, + 0x2d, + 0xd1, + 0xf0, + 0xd4, + 0x7f, + 0x59, + 0x67, + 0x21, + 0xc2, + 0x33, + 0xfd, + 0x9b, + 0x2e, + 0x99, + 0x19, + 0xac, + 0x91, + 0x28, + 0x8a, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x1b, + 0x5e, + 0x48, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 + ]) +} + + +pub fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("decode_hex_str ('hex_bytes' from stacks) <360>", |b| b.iter(|| decode_hex_str_stacks(black_box("00000000010400a468e72df6754387209827327b989f4a99542a69000000000000007700000000000000b40001231c213949455317d15ff25dfd7ad9bc0426cffa5c6f5be46e79fa1e182b6145180c1c135d6cccfcc49e85cb825e615228daf2d1663e49d70cd5d0e196d126c00302000000000005167b2dd1f0d47f596721c233fd9b2e9919ac91288a000000000c1b5e4800000000000000000000000000000000000000000000000000000000000000000000")))); + c.bench_function("decode_hex_str (function from crate 'hex') <360>", |b| b.iter(|| decode_hex_str_crate(black_box("00000000010400a468e72df6754387209827327b989f4a99542a69000000000000007700000000000000b40001231c213949455317d15ff25dfd7ad9bc0426cffa5c6f5be46e79fa1e182b6145180c1c135d6cccfcc49e85cb825e615228daf2d1663e49d70cd5d0e196d126c00302000000000005167b2dd1f0d47f596721c233fd9b2e9919ac91288a000000000c1b5e4800000000000000000000000000000000000000000000000000000000000000000000")))); + + c.bench_function("encode_to_hex_str ('to_hex' from stacks) <360>", |b| b.iter(|| encode_hex_str_stacks())); + c.bench_function("encode_to_hex_str (function from crate 'hex') <360>", |b| b.iter(|| encode_hex_str_crate())); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/components/chainhook-cli/benches/storage/redis.rs b/components/chainhook-cli/benches/storage/redis.rs new file mode 100644 index 0000000..0e5a849 --- /dev/null +++ b/components/chainhook-cli/benches/storage/redis.rs @@ -0,0 +1,17 @@ +use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use chainhook_event_indexer::ingestion::start_ingesting; +use chainhook_event_observer::indexer::IndexerConfig; + + +fn criterion_benchmark(c: &mut Criterion) { + let config = IndexerConfig { + stacks_node_rpc_url: "http://0.0.0.0:20443".into(), + bitcoin_node_rpc_url: "http://0.0.0.0:18443".into(), + bitcoin_node_rpc_username: "devnet".into(), + bitcoin_node_rpc_password: "devnet".into(), + }; + c.bench_function("redis", |b| b.iter(|| start_ingesting("/Users/ludovic/Downloads/stacks-blockchain-api.tsv".into(), config.clone()).unwrap())); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/components/chainhook-cli/benches/storage/rocksdb.rs b/components/chainhook-cli/benches/storage/rocksdb.rs new file mode 100644 index 0000000..4bec912 --- /dev/null +++ b/components/chainhook-cli/benches/storage/rocksdb.rs @@ -0,0 +1,16 @@ +use criterion::{black_box, criterion_group, criterion_main, Criterion}; + +fn ingest_tsv(n: u64) -> u64 { + match n { + 0 => 1, + 1 => 1, + n => fibonacci(n-1) + fibonacci(n-2), + } +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20)))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/components/chainhook-cli/benches/storage/sqlite.rs b/components/chainhook-cli/benches/storage/sqlite.rs new file mode 100644 index 0000000..4bec912 --- /dev/null +++ b/components/chainhook-cli/benches/storage/sqlite.rs @@ -0,0 +1,16 @@ +use criterion::{black_box, criterion_group, criterion_main, Criterion}; + +fn ingest_tsv(n: u64) -> u64 { + match n { + 0 => 1, + 1 => 1, + n => fibonacci(n-1) + fibonacci(n-2), + } +} + +fn criterion_benchmark(c: &mut Criterion) { + c.bench_function("fib 20", |b| b.iter(|| fibonacci(black_box(20)))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/README.md b/components/chainhook-cli/examples/arkadiko-data-indexing/README.md new file mode 100644 index 0000000..8dc2b76 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/README.md @@ -0,0 +1,61 @@ + +In a console, launch `redis-server` with the following command + +```bash +$ redis-server +``` + +In another console, we will launch `vault-monitor`. `vault-monitor` is a program that will be processing the events triggered by `chainhook-db`. Ruby on Rails (ruby 2.7+, rails 7+) was used to demonstrate that Chainhooks is a language agnostic layer. + +```bash +# Navigate to vault monitor directory +$ cd vault-monitor + +# Install dependencies +$ bundle install + +# Create database and run db migrations (will use sqlite in development mode) +$ rails db:migrate + +# Run program +$ rails server +``` + +`vault-monitor` exposes an admin readonly user interface at this address `http://localhost:3000/admin`. + +In another console, launch `chainhook-cli`, using the command: + +```bash +$ chainhook-cli replay --testnet +``` + +Finally, make `vault-monitor` register a chainhook, using the following command: + +```bash +curl -X "POST" "http://0.0.0.0:20446/v1/chainhooks/" \ + -H 'Content-Type: application/json' \ + -d $'{ + "stacks": { + "predicate": { + "type": "print_event", + "rule": { + "contains": "vault", + "contract_identifier": "SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-freddie-v1-1" + } + }, + "action": { + "http": { + "url": "http://localhost:3000/chainhooks/v1/vaults", + "method": "POST", + "authorization_header": "Bearer cn389ncoiwuencr" + } + }, + "uuid": "1", + "decode_clarity_values": true, + "version": 1, + "name": "Vault events observer", + "network": "mainnet" + } +}' +``` + diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitattributes b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitattributes new file mode 100644 index 0000000..31eeee0 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitattributes @@ -0,0 +1,7 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitignore b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitignore new file mode 100644 index 0000000..886f714 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.gitignore @@ -0,0 +1,35 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore uploaded files in development. +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +/public/assets + +# Ignore master key for decrypting credentials and more. +/config/master.key diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.ruby-version b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.ruby-version new file mode 100644 index 0000000..49cdd66 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/.ruby-version @@ -0,0 +1 @@ +2.7.6 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile new file mode 100644 index 0000000..b263853 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile @@ -0,0 +1,77 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby "2.7.6" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.3", ">= 7.0.3.1" + +# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] +gem "sprockets-rails" + +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" + +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" + +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" + +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +gem "redis", "~> 4.0" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +gem 'logging' +gem 'logging-rails' + +# Use Sass to process CSS +# gem "sassc-rails" + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +gem "administrate" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri mingw x64_mingw ] +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" + + # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] + # gem "rack-mini-profiler" + + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" + gem "webdrivers" +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile.lock b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile.lock new file mode 100644 index 0000000..25a6e4d --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Gemfile.lock @@ -0,0 +1,287 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.3.1) + actionpack (= 7.0.3.1) + activesupport (= 7.0.3.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.3.1) + actionpack (= 7.0.3.1) + activejob (= 7.0.3.1) + activerecord (= 7.0.3.1) + activestorage (= 7.0.3.1) + activesupport (= 7.0.3.1) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.3.1) + actionpack (= 7.0.3.1) + actionview (= 7.0.3.1) + activejob (= 7.0.3.1) + activesupport (= 7.0.3.1) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.3.1) + actionview (= 7.0.3.1) + activesupport (= 7.0.3.1) + rack (~> 2.0, >= 2.2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.3.1) + actionpack (= 7.0.3.1) + activerecord (= 7.0.3.1) + activestorage (= 7.0.3.1) + activesupport (= 7.0.3.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.3.1) + activesupport (= 7.0.3.1) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.3.1) + activesupport (= 7.0.3.1) + globalid (>= 0.3.6) + activemodel (7.0.3.1) + activesupport (= 7.0.3.1) + activerecord (7.0.3.1) + activemodel (= 7.0.3.1) + activesupport (= 7.0.3.1) + activestorage (7.0.3.1) + actionpack (= 7.0.3.1) + activejob (= 7.0.3.1) + activerecord (= 7.0.3.1) + activesupport (= 7.0.3.1) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.3.1) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + addressable (2.8.0) + public_suffix (>= 2.0.2, < 5.0) + administrate (0.18.0) + actionpack (>= 5.0) + actionview (>= 5.0) + activerecord (>= 5.0) + jquery-rails (>= 4.0) + kaminari (>= 1.0) + sassc-rails (~> 2.1) + selectize-rails (~> 0.6) + bindex (0.8.1) + bootsnap (1.13.0) + msgpack (~> 1.2) + builder (3.2.4) + capybara (3.37.1) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + childprocess (4.1.0) + concurrent-ruby (1.1.10) + crass (1.0.6) + debug (1.6.2) + irb (>= 1.3.6) + reline (>= 0.3.1) + digest (3.1.0) + erubi (1.11.0) + ffi (1.15.5) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.12.0) + concurrent-ruby (~> 1.0) + importmap-rails (1.1.5) + actionpack (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.5.11) + irb (1.4.1) + reline (>= 0.3.0) + jbuilder (2.11.5) + actionview (>= 5.0.0) + activesupport (>= 5.0.0) + jquery-rails (4.5.0) + rails-dom-testing (>= 1, < 3) + railties (>= 4.2.0) + thor (>= 0.14, < 2.0) + kaminari (1.2.2) + activesupport (>= 4.1.0) + kaminari-actionview (= 1.2.2) + kaminari-activerecord (= 1.2.2) + kaminari-core (= 1.2.2) + kaminari-actionview (1.2.2) + actionview + kaminari-core (= 1.2.2) + kaminari-activerecord (1.2.2) + activerecord + kaminari-core (= 1.2.2) + kaminari-core (1.2.2) + little-plugger (1.1.4) + logging (2.3.1) + little-plugger (~> 1.1) + multi_json (~> 1.14) + logging-rails (0.6.0) + logging (>= 1.8) + loofah (2.19.1) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.7.1) + mini_mime (>= 0.1.1) + marcel (1.0.2) + matrix (0.4.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.16.2) + msgpack (1.5.4) + multi_json (1.15.0) + net-imap (0.2.3) + digest + net-protocol + strscan + net-pop (0.1.1) + digest + net-protocol + timeout + net-protocol (0.1.3) + timeout + net-smtp (0.3.1) + digest + net-protocol + timeout + nio4r (2.5.8) + nokogiri (1.13.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.13.10-x86_64-linux) + racc (~> 1.4) + public_suffix (4.0.7) + puma (5.6.4) + nio4r (~> 2.0) + racc (1.6.1) + rack (2.2.4) + rack-test (2.0.2) + rack (>= 1.3) + rails (7.0.3.1) + actioncable (= 7.0.3.1) + actionmailbox (= 7.0.3.1) + actionmailer (= 7.0.3.1) + actionpack (= 7.0.3.1) + actiontext (= 7.0.3.1) + actionview (= 7.0.3.1) + activejob (= 7.0.3.1) + activemodel (= 7.0.3.1) + activerecord (= 7.0.3.1) + activestorage (= 7.0.3.1) + activesupport (= 7.0.3.1) + bundler (>= 1.15.0) + railties (= 7.0.3.1) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.4.4) + loofah (~> 2.19, >= 2.19.1) + railties (7.0.3.1) + actionpack (= 7.0.3.1) + activesupport (= 7.0.3.1) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + redis (4.7.1) + regexp_parser (2.5.0) + reline (0.3.1) + io-console (~> 0.5) + rexml (3.2.5) + rubyzip (2.3.2) + sassc (2.4.0) + ffi (~> 1.9) + sassc-rails (2.1.2) + railties (>= 4.0.0) + sassc (>= 2.0) + sprockets (> 3.0) + sprockets-rails + tilt + selectize-rails (0.12.6) + selenium-webdriver (4.4.0) + childprocess (>= 0.5, < 5.0) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + sprockets (4.1.1) + concurrent-ruby (~> 1.0) + rack (> 1, < 3) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.4.4) + stimulus-rails (1.1.0) + railties (>= 6.0.0) + strscan (3.0.4) + thor (1.2.1) + tilt (2.0.11) + timeout (0.3.0) + turbo-rails (1.1.1) + actionpack (>= 6.0.0) + activejob (>= 6.0.0) + railties (>= 6.0.0) + tzinfo (2.0.5) + concurrent-ruby (~> 1.0) + web-console (4.2.0) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + webdrivers (5.0.0) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (~> 4.0) + websocket (1.2.9) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.6.0) + +PLATFORMS + arm64-darwin-21 + x86_64-linux + +DEPENDENCIES + administrate + bootsnap + capybara + debug + importmap-rails + jbuilder + logging + logging-rails + puma (~> 5.0) + rails (~> 7.0.3, >= 7.0.3.1) + redis (~> 4.0) + selenium-webdriver + sprockets-rails + sqlite3 (~> 1.4) + stimulus-rails + turbo-rails + tzinfo-data + web-console + webdrivers + +RUBY VERSION + ruby 2.7.6p219 + +BUNDLED WITH + 2.3.20 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/README.md b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/README.md new file mode 100644 index 0000000..fa0d724 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/README.md @@ -0,0 +1,19 @@ +# Use case: USDA collateral monitoring + +* Ruby version: 2 + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Rakefile b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Rakefile new file mode 100644 index 0000000..9a5ea73 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/config/manifest.js b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/config/manifest.js new file mode 100644 index 0000000..ddd546a --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/config/manifest.js @@ -0,0 +1,4 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css +//= link_tree ../../javascript .js +//= link_tree ../../../vendor/javascript .js diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/images/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/images/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/stylesheets/application.css b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/stylesheets/application.css new file mode 100644 index 0000000..288b9ab --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/chainhooks/observe_vaults.json b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/chainhooks/observe_vaults.json new file mode 100644 index 0000000..3376759 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/chainhooks/observe_vaults.json @@ -0,0 +1,23 @@ +{ + "stacks": { + "uuid": "1", + "name": "Vault events observer", + "network": "mainnet", + "version": 1, + "decode_clarity_values": true, + "predicate": { + "type": "print_event", + "rule": { + "contract_identifier": "SP2C2YFP12AJZB4MABJBAJ55XECVS7E4PMMZ89YZR.arkadiko-freddie-v1-1", + "contains": "vault" + } + }, + "action": { + "http": { + "url": "http://localhost:3000/chainhooks/v1/vaults", + "method": "POST", + "authorization_header": "Bearer cn389ncoiwuencr" + } + } + } +} \ No newline at end of file diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/channel.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/channel.rb new file mode 100644 index 0000000..d672697 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/connection.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/connection.rb new file mode 100644 index 0000000..0ff5442 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/application_controller.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/application_controller.rb new file mode 100644 index 0000000..f2cffea --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/application_controller.rb @@ -0,0 +1,21 @@ +# All Administrate controllers inherit from this +# `Administrate::ApplicationController`, making it the ideal place to put +# authentication logic or other before_actions. +# +# If you want to add pagination or other controller-level concerns, +# you're free to overwrite the RESTful controller actions. +module Admin + class ApplicationController < Administrate::ApplicationController + before_action :authenticate_admin + + def authenticate_admin + # TODO Add authentication logic here. + end + + # Override this value to specify the number of elements to display at a time + # on index pages. Defaults to 20. + # def records_per_page + # params[:per_page] || 20 + # end + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/vaults_controller.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/vaults_controller.rb new file mode 100644 index 0000000..17ec481 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/admin/vaults_controller.rb @@ -0,0 +1,47 @@ +module Admin + class VaultsController < Admin::ApplicationController + + # Overwrite any of the RESTful controller actions to implement custom behavior + # For example, you may want to send an email after a foo is updated. + # + # def update + # super + # send_foo_updated_email(requested_resource) + # end + + # Override this method to specify custom lookup behavior. + # This will be used to set the resource for the `show`, `edit`, and `update` + # actions. + # + # def find_resource(param) + # Foo.find_by!(slug: param) + # end + + # The result of this lookup will be available as `requested_resource` + + # Override this if you have certain roles that require a subset + # this will be used to set the records shown on the `index` action. + # + # def scoped_resource + # if current_user.super_admin? + # resource_class + # else + # resource_class.with_less_stuff + # end + # end + + # Override `resource_params` if you want to transform the submitted + # data before it's persisted. For example, the following would turn all + # empty values into nil values. It uses other APIs such as `resource_class` + # and `dashboard`: + # + # def resource_params + # params.require(resource_class.model_name.param_key). + # permit(dashboard.permitted_attributes). + # transform_values { |value| value == "" ? nil : value } + # end + + # See https://administrate-prototype.herokuapp.com/customizing_controller_actions + # for more information + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/application_controller.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/application_controller.rb new file mode 100644 index 0000000..09705d1 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/chainhooks_controller.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/chainhooks_controller.rb new file mode 100644 index 0000000..3db150e --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/chainhooks_controller.rb @@ -0,0 +1,28 @@ +class ChainhooksController < ApplicationController + skip_before_action :verify_authenticity_token + wrap_parameters false + + def vaults + payload = JSON.parse request.body.read + payload["apply"].each do |block| + block["transactions"].each do |transaction| + transaction["metadata"]["receipt"]["events"].each do |event| + next if event["type"] != "SmartContractEvent" + event_data = event["data"]["value"] + next if event_data.nil? || event_data["type"] != "vault" + vault_event_data = event_data["data"] + if event_data["action"] == "created" + Vault.create_from_onchain_event(vault_event_data) + elsif ["deposit", "burn", "close", "mint"].include? event_data["action"] + Vault.update_attributes_from_onchain_event(vault_event_data) + else + p "Unknown event type #{event_data["action"]}" + end + end + end + end + respond_to do |format| + format.json { head :no_content, status: :ok } + end + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/concerns/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/vaults_controller.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/vaults_controller.rb new file mode 100644 index 0000000..a0a1844 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/controllers/vaults_controller.rb @@ -0,0 +1,70 @@ +class VaultsController < ApplicationController + before_action :set_vault, only: %i[ show edit update destroy ] + + # GET /vaults or /vaults.json + def index + @vaults = Vault.all + end + + # GET /vaults/1 or /vaults/1.json + def show + end + + # GET /vaults/new + def new + @vault = Vault.new + end + + # GET /vaults/1/edit + def edit + end + + # POST /vaults or /vaults.json + def create + @vault = Vault.new(vault_params) + + respond_to do |format| + if @vault.save + format.html { redirect_to vault_url(@vault), notice: "Vault was successfully created." } + format.json { render :show, status: :created, location: @vault } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @vault.errors, status: :unprocessable_entity } + end + end + end + + # PATCH/PUT /vaults/1 or /vaults/1.json + def update + respond_to do |format| + if @vault.update(vault_params) + format.html { redirect_to vault_url(@vault), notice: "Vault was successfully updated." } + format.json { render :show, status: :ok, location: @vault } + else + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @vault.errors, status: :unprocessable_entity } + end + end + end + + # DELETE /vaults/1 or /vaults/1.json + def destroy + @vault.destroy + + respond_to do |format| + format.html { redirect_to vaults_url, notice: "Vault was successfully destroyed." } + format.json { head :no_content } + end + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_vault + @vault = Vault.find(params[:id]) + end + + # Only allow a list of trusted parameters through. + def vault_params + params.require(:vault).permit(:id, :owner, :collateral, :collateral_type, :collateral_token, :stacked_tokens, :stacker_name, :revoked_stacking, :auto_payoff, :debt, :created_at_block_height, :updated_at_block_height, :stability_fee_accrued, :stability_fee_last_accrued, :is_liquidated, :auction_ended, :leftover_collateral) + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/dashboards/vault_dashboard.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/dashboards/vault_dashboard.rb new file mode 100644 index 0000000..acf22f3 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/dashboards/vault_dashboard.rb @@ -0,0 +1,122 @@ +require "administrate/base_dashboard" + +class VaultDashboard < Administrate::BaseDashboard + # ATTRIBUTE_TYPES + # a hash that describes the type of each of the model's fields. + # + # Each different type represents an Administrate::Field object, + # which determines how the attribute is displayed + # on pages throughout the dashboard. + ATTRIBUTE_TYPES = { + id: Field::Number, + auction_ended: Field::Boolean, + auto_payoff: Field::Boolean, + collateral: Field::Number, + collateral_token: Field::String, + collateral_type: Field::String, + created_at_block_height: Field::Number, + debt: Field::Number, + is_liquidated: Field::Boolean, + leftover_collateral: Field::Number, + onchain_id: Field::Number, + owner: Field::String, + revoked_stacking: Field::Boolean, + stability_fee_accrued: Field::Number, + stability_fee_last_accrued: Field::Number, + stacked_tokens: Field::Number, + stacker_name: Field::String, + updated_at_block_height: Field::Number, + created_at: Field::DateTime, + updated_at: Field::DateTime, + }.freeze + + # COLLECTION_ATTRIBUTES + # an array of attributes that will be displayed on the model's index page. + # + # By default, it's limited to four items to reduce clutter on index pages. + # Feel free to add, remove, or rearrange items. + COLLECTION_ATTRIBUTES = %i[ + onchain_id + created_at_block_height + collateral_token + collateral_type + collateral + debt + stacked_tokens + owner + ].freeze + + # SHOW_PAGE_ATTRIBUTES + # an array of attributes that will be displayed on the model's show page. + SHOW_PAGE_ATTRIBUTES = %i[ + auction_ended + auto_payoff + collateral + collateral_token + collateral_type + created_at_block_height + debt + is_liquidated + leftover_collateral + onchain_id + owner + revoked_stacking + stability_fee_accrued + stability_fee_last_accrued + stacked_tokens + stacker_name + updated_at_block_height + ].freeze + + # FORM_ATTRIBUTES + # an array of attributes that will be displayed + # on the model's form (`new` and `edit`) pages. + FORM_ATTRIBUTES = %i[ + auction_ended + auto_payoff + collateral + collateral_token + collateral_type + created_at_block_height + debt + is_liquidated + leftover_collateral + onchain_id + owner + revoked_stacking + stability_fee_accrued + stability_fee_last_accrued + stacked_tokens + stacker_name + updated_at_block_height + ].freeze + + # COLLECTION_FILTERS + # a hash that defines filters that can be used while searching via the search + # field of the dashboard. + # + # For example to add an option to search for open resources by typing "open:" + # in the search field: + # + # COLLECTION_FILTERS = { + # open: ->(resources) { resources.where(open: true) } + # }.freeze + COLLECTION_FILTERS = {}.freeze + + # disable 'edit' and 'destroy' links + def valid_action?(name, resource = resource_class) + %w[edit destroy].exclude?(name.to_s) && super + end + + def default_sorting_attribute + :age + end + + def default_sorting_direction + :desc + end + + def display_resource(vault) + "Vault ##{vault.onchain_id}" + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/application_helper.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/vaults_helper.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/vaults_helper.rb new file mode 100644 index 0000000..329b588 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/helpers/vaults_helper.rb @@ -0,0 +1,2 @@ +module VaultsHelper +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/application.js b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/application.js new file mode 100644 index 0000000..0d7b494 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/application.js b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/application.js new file mode 100644 index 0000000..1213e85 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/hello_controller.js b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/hello_controller.js new file mode 100644 index 0000000..5975c07 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/index.js b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/index.js new file mode 100644 index 0000000..54ad4ca --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/javascript/controllers/index.js @@ -0,0 +1,11 @@ +// Import and register all your controllers from the importmap under controllers/* + +import { application } from "controllers/application" + +// Eager load all controllers defined in the import map under controllers/**/*_controller +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) + +// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) +// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" +// lazyLoadControllersFrom("controllers", application) diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/jobs/application_job.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/jobs/application_job.rb new file mode 100644 index 0000000..d394c3d --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/mailers/application_mailer.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/mailers/application_mailer.rb new file mode 100644 index 0000000..3c34c81 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/application_record.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/application_record.rb new file mode 100644 index 0000000..b63caeb --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/concerns/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/vault.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/vault.rb new file mode 100644 index 0000000..89cff1c --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/models/vault.rb @@ -0,0 +1,48 @@ +class Vault < ApplicationRecord + + def Vault.create_from_onchain_event(params) + Vault.create({ + :onchain_id => params["id"], + :owner => params["owner"], + :collateral => params["collateral"], + :collateral_type => params["collateral-type"], + :collateral_token => params["collateral-token"], + :stacked_tokens => params["stacked-tokens"], + :stacker_name => params["stacker-name"], + :revoked_stacking => params["revoked-stacking"], + :auto_payoff => params["auto-payoff"], + :debt => params["debt"], + :created_at_block_height => params["created-at-block-height"], + :updated_at_block_height => params["updated-at-block-height"], + :stability_fee_accrued => params["stability-fee-accrued"], + :stability_fee_last_accrued => params["stability-fee-last-accrued"], + :is_liquidated => params["is-liquidated"], + :auction_ended => params["auction-ended"], + :leftover_collateral => params["leftover-collateral"], + }) + end + + def Vault.update_attributes_from_onchain_event(params) + Vault + .where(:onchain_id => params["id"]) + .update_all( + :owner => params["owner"], + :collateral => params["collateral"], + :collateral_type => params["collateral-type"], + :collateral_token => params["collateral-token"], + :stacked_tokens => params["stacked-tokens"], + :stacker_name => params["stacker-name"], + :revoked_stacking => params["revoked-stacking"], + :auto_payoff => params["auto-payoff"], + :debt => params["debt"], + :created_at_block_height => params["created-at-block-height"], + :updated_at_block_height => params["updated-at-block-height"], + :stability_fee_accrued => params["stability-fee-accrued"], + :stability_fee_last_accrued => params["stability-fee-last-accrued"], + :is_liquidated => params["is-liquidated"], + :auction_ended => params["auction-ended"], + :leftover_collateral => params["leftover-collateral"], + ) + end + +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/_collection.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/_collection.html.erb new file mode 100644 index 0000000..f176fb6 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/_collection.html.erb @@ -0,0 +1,76 @@ +<%# +# Collection + +This partial is used on the `index` and `show` pages +to display a collection of resources in an HTML table. + +## Local variables: + +- `collection_presenter`: + An instance of [Administrate::Page::Collection][1]. + The table presenter uses `ResourceDashboard::COLLECTION_ATTRIBUTES` to determine + the columns displayed in the table +- `resources`: + An ActiveModel::Relation collection of resources to be displayed in the table. + By default, the number of resources is limited by pagination + or by a hard limit to prevent excessive page load times + +[1]: http://www.rubydoc.info/gems/administrate/Administrate/Page/Collection +%> + + + + + <% collection_presenter.attribute_types.each do |attr_name, attr_type| %> + + <% end %> + + + + + <% resources.each do |resource| %> + + <%= %(tabindex=0 role=link data-url=#{polymorphic_path([namespace, resource])}) %> + <% end %> + > + <% collection_presenter.attributes_for(resource).each do |attribute| %> + + <% end %> + + <% end %> + +
" + scope="col" + role="columnheader" + aria-sort="<%= sort_order(collection_presenter.ordered_html_class(attr_name)) %>"> + <%= link_to(sanitized_order_params(page, collection_field_name).merge( + collection_presenter.order_params_for(attr_name, key: collection_field_name) + )) do %> + <%= t( + "helpers.label.#{collection_presenter.resource_name}.#{attr_name}", + default: resource_class.human_attribute_name(attr_name), + ).titleize %> + <% if collection_presenter.ordered_by?(attr_name) %> + + + + <% end %> + <% end %> +
+ <% if accessible_action?(resource, :show) -%> + + <%= render_field attribute %> + + <% else %> + <%= render_field attribute %> + <% end -%> +
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/index.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/index.html.erb new file mode 100644 index 0000000..0b21bb9 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/index.html.erb @@ -0,0 +1,21 @@ +<%= + render("index_header", + resources: resources, + search_term: search_term, + page: page, + show_search_bar: show_search_bar, + ) +%> + +
+ <%= render( + "collection", + collection_presenter: page, + collection_field_name: resource_name, + page: page, + resources: resources, + table_title: "page-title" + ) %> + + <%= render("pagination", resources: resources) %> +
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/show.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/show.html.erb new file mode 100644 index 0000000..4a44512 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/admin/vaults/show.html.erb @@ -0,0 +1,23 @@ +<% content_for(:title) { t("administrate.actions.show_resource", name: page.page_title) } %> + + + +
+
+ <% page.attributes.each do |attribute| %> +
+ <%= t( + "helpers.label.#{resource_name}.#{attribute.name}", + default: page.resource.class.human_attribute_name(attribute.name), + ) %> +
+ +
<%= render_field attribute, page: page %>
+ <% end %> +
+
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/application.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/application.html.erb new file mode 100644 index 0000000..941bfaf --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/application.html.erb @@ -0,0 +1,16 @@ + + + + UsdaCollateralMonitor + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= yield %> + + diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000..cbd34d2 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.text.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000..37f0bdd --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_form.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_form.html.erb new file mode 100644 index 0000000..b5fe64a --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_form.html.erb @@ -0,0 +1,102 @@ +<%= form_with(model: vault) do |form| %> + <% if vault.errors.any? %> +
+

<%= pluralize(vault.errors.count, "error") %> prohibited this vault from being saved:

+ +
    + <% vault.errors.each do |error| %> +
  • <%= error.full_message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :id, style: "display: block" %> + <%= form.number_field :id %> +
+ +
+ <%= form.label :owner, style: "display: block" %> + <%= form.text_field :owner %> +
+ +
+ <%= form.label :collateral, style: "display: block" %> + <%= form.number_field :collateral %> +
+ +
+ <%= form.label :collateral_type, style: "display: block" %> + <%= form.text_field :collateral_type %> +
+ +
+ <%= form.label :collateral_token, style: "display: block" %> + <%= form.text_field :collateral_token %> +
+ +
+ <%= form.label :stacked_tokens, style: "display: block" %> + <%= form.number_field :stacked_tokens %> +
+ +
+ <%= form.label :stacker_name, style: "display: block" %> + <%= form.text_field :stacker_name %> +
+ +
+ <%= form.label :revoked_stacking, style: "display: block" %> + <%= form.check_box :revoked_stacking %> +
+ +
+ <%= form.label :auto_payoff, style: "display: block" %> + <%= form.check_box :auto_payoff %> +
+ +
+ <%= form.label :debt, style: "display: block" %> + <%= form.number_field :debt %> +
+ +
+ <%= form.label :created_at_block_height, style: "display: block" %> + <%= form.number_field :created_at_block_height %> +
+ +
+ <%= form.label :updated_at_block_height, style: "display: block" %> + <%= form.number_field :updated_at_block_height %> +
+ +
+ <%= form.label :stability_fee_accrued, style: "display: block" %> + <%= form.number_field :stability_fee_accrued %> +
+ +
+ <%= form.label :stability_fee_last_accrued, style: "display: block" %> + <%= form.number_field :stability_fee_last_accrued %> +
+ +
+ <%= form.label :is_liquidated, style: "display: block" %> + <%= form.check_box :is_liquidated %> +
+ +
+ <%= form.label :auction_ended, style: "display: block" %> + <%= form.check_box :auction_ended %> +
+ +
+ <%= form.label :leftover_collateral, style: "display: block" %> + <%= form.number_field :leftover_collateral %> +
+ +
+ <%= form.submit %> +
+<% end %> diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.html.erb new file mode 100644 index 0000000..d809396 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.html.erb @@ -0,0 +1,87 @@ +
+

+ Id: + <%= vault.id %> +

+ +

+ Owner: + <%= vault.owner %> +

+ +

+ Collateral: + <%= vault.collateral %> +

+ +

+ Collateral type: + <%= vault.collateral_type %> +

+ +

+ Collateral token: + <%= vault.collateral_token %> +

+ +

+ Stacked tokens: + <%= vault.stacked_tokens %> +

+ +

+ Stacker name: + <%= vault.stacker_name %> +

+ +

+ Revoked stacking: + <%= vault.revoked_stacking %> +

+ +

+ Auto payoff: + <%= vault.auto_payoff %> +

+ +

+ Debt: + <%= vault.debt %> +

+ +

+ Created at block height: + <%= vault.created_at_block_height %> +

+ +

+ Updated at block height: + <%= vault.updated_at_block_height %> +

+ +

+ Stability fee accrued: + <%= vault.stability_fee_accrued %> +

+ +

+ Stability fee last accrued: + <%= vault.stability_fee_last_accrued %> +

+ +

+ Is liquidated: + <%= vault.is_liquidated %> +

+ +

+ Auction ended: + <%= vault.auction_ended %> +

+ +

+ Leftover collateral: + <%= vault.leftover_collateral %> +

+ +
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.json.jbuilder b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.json.jbuilder new file mode 100644 index 0000000..2ba636b --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/_vault.json.jbuilder @@ -0,0 +1,2 @@ +json.extract! vault, :id, :id, :owner, :collateral, :collateral_type, :collateral_token, :stacked_tokens, :stacker_name, :revoked_stacking, :auto_payoff, :debt, :created_at_block_height, :updated_at_block_height, :stability_fee_accrued, :stability_fee_last_accrued, :is_liquidated, :auction_ended, :leftover_collateral, :created_at, :updated_at +json.url vault_url(vault, format: :json) diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/edit.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/edit.html.erb new file mode 100644 index 0000000..e70ec38 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/edit.html.erb @@ -0,0 +1,10 @@ +

Editing vault

+ +<%= render "form", vault: @vault %> + +
+ +
+ <%= link_to "Show this vault", @vault %> | + <%= link_to "Back to vaults", vaults_path %> +
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.html.erb new file mode 100644 index 0000000..e75ae6b --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.html.erb @@ -0,0 +1,14 @@ +

<%= notice %>

+ +

Vaults

+ +
+ <% @vaults.each do |vault| %> + <%= render vault %> +

+ <%= link_to "Show this vault", vault %> +

+ <% end %> +
+ +<%= link_to "New vault", new_vault_path %> diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.json.jbuilder b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.json.jbuilder new file mode 100644 index 0000000..70f4fd7 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @vaults, partial: "vaults/vault", as: :vault diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/new.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/new.html.erb new file mode 100644 index 0000000..8d6e2a9 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/new.html.erb @@ -0,0 +1,9 @@ +

New vault

+ +<%= render "form", vault: @vault %> + +
+ +
+ <%= link_to "Back to vaults", vaults_path %> +
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.html.erb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.html.erb new file mode 100644 index 0000000..bf41bc5 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.html.erb @@ -0,0 +1,10 @@ +

<%= notice %>

+ +<%= render @vault %> + +
+ <%= link_to "Edit this vault", edit_vault_path(@vault) %> | + <%= link_to "Back to vaults", vaults_path %> + + <%= button_to "Destroy this vault", @vault, method: :delete %> +
diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.json.jbuilder b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.json.jbuilder new file mode 100644 index 0000000..22c16f8 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/app/views/vaults/show.json.jbuilder @@ -0,0 +1 @@ +json.partial! "vaults/vault", vault: @vault diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/bundle b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/bundle new file mode 100755 index 0000000..981e650 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/bundle @@ -0,0 +1,114 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + requirement = bundler_gem_version.approximate_recommendation + + return requirement unless Gem.rubygems_version < Gem::Version.new("2.7.0") + + requirement += ".a" if bundler_gem_version.prerelease? + + requirement + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/importmap b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/importmap new file mode 100755 index 0000000..36502ab --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rails b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rails new file mode 100755 index 0000000..efc0377 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rake b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rake new file mode 100755 index 0000000..4fbf10b --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/setup b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/setup new file mode 100755 index 0000000..ec47b79 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config.ru b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config.ru new file mode 100644 index 0000000..4a3c09a --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/application.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/application.rb new file mode 100644 index 0000000..dbbd4e2 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/application.rb @@ -0,0 +1,26 @@ +require_relative "boot" + +require "rails/all" +# require 'logging' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module UsdaCollateralMonitor + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + # logger = Logging.logger(STDOUT) + # logger.level = :warn + # config.logger = logger + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/boot.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/boot.rb new file mode 100644 index 0000000..988a5dd --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/cable.yml b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/cable.yml new file mode 100644 index 0000000..0e289f2 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/cable.yml @@ -0,0 +1,11 @@ +development: + adapter: redis + url: redis://localhost:6379/1 + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: usda_collateral_monitor_production diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/credentials.yml.enc b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/credentials.yml.enc new file mode 100644 index 0000000..81bc422 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/credentials.yml.enc @@ -0,0 +1 @@ +M9q7nviDmGHWs2Gkx0rB0V86JvtEVq7k/lEZOJV6QncuIokTVvNr6kTEw4O5+kGqdAWxUrkfc3pBgWAcBNes4D3PHWWNPtX+wIPfRFfoVcG7kTGTGIqKq4VTieFKo8lx8Qv/CAZxxyXBSr+Nd2jUoW8p1cItSlUmQ01L6+4/m1Njzgxa+R7w6Trk/1OeNl0mb9P6po4jl1H4+6hNAsnnjlxBCoQdNy7FpuCv7498p+wOW9CbN5DCcG/ix347F4IN9JR9WwkUTbik1EkmjCKBox64cAlZBu8lsESMPEWMLfnztAK3di8r9HnsTgFSHcpjJsd1joZoY1+GCS9vbTrhsGB3HruENitIFyn+87C9QRa98FNOfQ7x9fY70xKbWAaoFmTdoxVQgTv3i8X10r6buhb5rnSnW2PvC1A/--ZiIEclsKkI3k+lA/--6USfkiHlZbWLbzOrXcbp4Q== \ No newline at end of file diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/database.yml b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/database.yml new file mode 100644 index 0000000..fcba57f --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environment.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environment.rb new file mode 100644 index 0000000..cac5315 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/development.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/development.rb new file mode 100644 index 0000000..a93717c --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/development.rb @@ -0,0 +1,76 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # Set the logging destination(s) + config.log_to = %w[stdout file] + + # Show the logging configuration on STDOUT + config.show_log_configuration = true +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/production.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/production.rb new file mode 100644 index 0000000..5fdc843 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/production.rb @@ -0,0 +1,99 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "usda_collateral_monitor_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Set the logging destination(s) + config.log_to = %w[file] + + # Show the logging configuration on STDOUT + config.show_log_configuration = false +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/test.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/test.rb new file mode 100644 index 0000000..6ea4d1e --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/environments/test.rb @@ -0,0 +1,60 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Turn false under Spring and add config.action_view.cache_template_loading = true. + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/importmap.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/importmap.rb new file mode 100644 index 0000000..8dce42d --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application", preload: true +pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true +pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/assets.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/assets.rb new file mode 100644 index 0000000..2eeef96 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/assets.rb @@ -0,0 +1,12 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/content_security_policy.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/content_security_policy.rb new file mode 100644 index 0000000..54f47cf --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap and inline scripts +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/filter_parameter_logging.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..adc6568 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/inflections.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/inflections.rb new file mode 100644 index 0000000..3860f65 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/permissions_policy.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/permissions_policy.rb new file mode 100644 index 0000000..00f64d7 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/initializers/permissions_policy.rb @@ -0,0 +1,11 @@ +# Define an application-wide HTTP permissions policy. For further +# information see https://developers.google.com/web/updates/2018/06/feature-policy +# +# Rails.application.config.permissions_policy do |f| +# f.camera :none +# f.gyroscope :none +# f.microphone :none +# f.usb :none +# f.fullscreen :self +# f.payment :self, "https://secure.example.com" +# end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/locales/en.yml b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/locales/en.yml new file mode 100644 index 0000000..8ca56fc --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# "true": "foo" +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/logging.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/logging.rb new file mode 100644 index 0000000..091ffa6 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/logging.rb @@ -0,0 +1,113 @@ +Logging::Rails.configure do |config| + + # Configure the Logging framework with the default log levels + Logging.init %w[debug info warn error fatal] + + # Objects will be converted to strings using the :inspect method. + Logging.format_as :inspect + + # The default layout used by the appenders. + layout = Logging.layouts.pattern(:pattern => '[%d] %-5l %c : %m\n') + + # Setup a color scheme called 'bright' than can be used to add color codes + # to the pattern layout. Color schemes should only be used with appenders + # that write to STDOUT or STDERR; inserting terminal color codes into a file + # is generally considered bad form. + Logging.color_scheme( 'bright', + :levels => { + :info => :green, + :warn => :yellow, + :error => :red, + :fatal => [:white, :on_red] + }, + :date => :blue, + :logger => :cyan, + :message => :magenta + ) + + # Configure an appender that will write log events to STDOUT. A colorized + # pattern layout is used to format the log events into strings before + # writing. + Logging.appenders.stdout( 'stdout', + :auto_flushing => true, + :layout => Logging.layouts.pattern( + :pattern => '[%d] %-5l %c : %m\n', + :color_scheme => 'bright' + ) + ) if config.log_to.include? 'stdout' + + # Configure an appender that will write log events to a file. The file will + # be rolled on a daily basis, and the past 7 rolled files will be kept. + # Older files will be deleted. The default pattern layout is used when + # formatting log events into strings. + Logging.appenders.rolling_file( 'file', + :filename => config.paths['log'].first, + :keep => 7, + :age => 'daily', + :truncate => false, + :auto_flushing => true, + :layout => layout + ) if config.log_to.include? 'file' + +=begin + # NOTE: You will need to install the `logging-email` gem to use this appender + # with loggging-2.0. The email appender was extracted into a plugin gem. That + # is the reason this code is commented out. + # + # Configure an appender that will send an email for "error" and "fatal" log + # events. All other log events will be ignored. Furthermore, log events will + # be buffered for one minute (or 200 events) before an email is sent. This + # is done to prevent a flood of messages. + Logging.appenders.email( 'email', + :from => "server@#{config.action_mailer.smtp_settings[:domain]}", + :to => "developers@#{config.action_mailer.smtp_settings[:domain]}", + :subject => "Rails Error [#{%x(uname -n).strip}]", + :server => config.action_mailer.smtp_settings[:address], + :domain => config.action_mailer.smtp_settings[:domain], + :acct => config.action_mailer.smtp_settings[:user_name], + :passwd => config.action_mailer.smtp_settings[:password], + :authtype => config.action_mailer.smtp_settings[:authentication], + + :auto_flushing => 200, # send an email after 200 messages have been buffered + :flush_period => 60, # send an email after one minute + :level => :error, # only process log events that are "error" or "fatal" + :layout => layout + ) if config.log_to.include? 'email' +=end + + # Setup the root logger with the Rails log level and the desired set of + # appenders. The list of appenders to use should be set in the environment + # specific configuration file. + # + # For example, in a production application you would not want to log to + # STDOUT, but you would want to send an email for "error" and "fatal" + # messages: + # + # => config/environments/production.rb + # + # config.log_to = %w[file email] + # + # In development you would want to log to STDOUT and possibly to a file: + # + # => config/environments/development.rb + # + # config.log_to = %w[stdout file] + # + Logging.logger.root.level = config.log_level + Logging.logger.root.appenders = config.log_to unless config.log_to.empty? + Logging.logger['ActionController::Base'].level = :warn + + # Under Phusion Passenger smart spawning, we need to reopen all IO streams + # after workers have forked. + # + # The rolling file appender uses shared file locks to ensure that only one + # process will roll the log file. Each process writing to the file must have + # its own open file descriptor for `flock` to function properly. Reopening + # the file descriptors after forking ensures that each worker has a unique + # file descriptor. + if defined? PhusionPassenger + PhusionPassenger.on_event(:starting_worker_process) do |forked| + Logging.reopen if forked + end + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/puma.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/puma.rb new file mode 100644 index 0000000..daaf036 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/routes.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/routes.rb new file mode 100644 index 0000000..bcc4aa5 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/routes.rb @@ -0,0 +1,8 @@ +Rails.application.routes.draw do + namespace :admin do + resources :vaults, only: %i(index show) + root to: "vaults#index" + end + + post '/chainhooks/v1/vaults', to: 'chainhooks#vaults' +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/storage.yml b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/storage.yml new file mode 100644 index 0000000..4942ab6 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/migrate/20220817092514_create_vaults.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/migrate/20220817092514_create_vaults.rb new file mode 100644 index 0000000..1b28e22 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/migrate/20220817092514_create_vaults.rb @@ -0,0 +1,25 @@ +class CreateVaults < ActiveRecord::Migration[7.0] + def change + create_table :vaults do |t| + t.integer :onchain_id + t.string :owner + t.integer :collateral + t.string :collateral_type + t.string :collateral_token + t.integer :stacked_tokens + t.string :stacker_name + t.boolean :revoked_stacking + t.boolean :auto_payoff + t.integer :debt + t.integer :created_at_block_height + t.integer :updated_at_block_height + t.integer :stability_fee_accrued + t.integer :stability_fee_last_accrued + t.boolean :is_liquidated + t.boolean :auction_ended + t.integer :leftover_collateral + + t.timestamps + end + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/schema.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/schema.rb new file mode 100644 index 0000000..334900e --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/schema.rb @@ -0,0 +1,36 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[7.0].define(version: 2022_08_17_092514) do + create_table "vaults", force: :cascade do |t| + t.integer "onchain_id" + t.string "owner" + t.integer "collateral" + t.string "collateral_type" + t.string "collateral_token" + t.integer "stacked_tokens" + t.string "stacker_name" + t.boolean "revoked_stacking" + t.boolean "auto_payoff" + t.integer "debt" + t.integer "created_at_block_height" + t.integer "updated_at_block_height" + t.integer "stability_fee_accrued" + t.integer "stability_fee_last_accrued" + t.boolean "is_liquidated" + t.boolean "auction_ended" + t.integer "leftover_collateral" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/seeds.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/seeds.rb new file mode 100644 index 0000000..bc25fce --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) +# Character.create(name: "Luke", movie: movies.first) diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/lib/assets/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/lib/assets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/lib/tasks/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/log/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/404.html b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/404.html new file mode 100644 index 0000000..2be3af2 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/422.html b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/422.html new file mode 100644 index 0000000..c08eac0 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/500.html b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/500.html new file mode 100644 index 0000000..78a030a --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/apple-touch-icon-precomposed.png b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/apple-touch-icon-precomposed.png new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/apple-touch-icon.png b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/apple-touch-icon.png new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/favicon.ico b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/robots.txt b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/robots.txt new file mode 100644 index 0000000..c19f78a --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/storage/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/storage/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/application_system_test_case.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/application_system_test_case.rb new file mode 100644 index 0000000..d19212a --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/channels/application_cable/connection_test.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/channels/application_cable/connection_test.rb new file mode 100644 index 0000000..800405f --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/channels/application_cable/connection_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/vaults_controller_test.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/vaults_controller_test.rb new file mode 100644 index 0000000..8134a57 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/controllers/vaults_controller_test.rb @@ -0,0 +1,48 @@ +require "test_helper" + +class VaultsControllerTest < ActionDispatch::IntegrationTest + setup do + @vault = vaults(:one) + end + + test "should get index" do + get vaults_url + assert_response :success + end + + test "should get new" do + get new_vault_url + assert_response :success + end + + test "should create vault" do + assert_difference("Vault.count") do + post vaults_url, params: { vault: { auction_ended: @vault.auction_ended, auto_payoff: @vault.auto_payoff, collateral: @vault.collateral, collateral_token: @vault.collateral_token, collateral_type: @vault.collateral_type, created_at_block_height: @vault.created_at_block_height, debt: @vault.debt, id: @vault.id, is_liquidated: @vault.is_liquidated, leftover_collateral: @vault.leftover_collateral, owner: @vault.owner, revoked_stacking: @vault.revoked_stacking, stability_fee_accrued: @vault.stability_fee_accrued, stability_fee_last_accrued: @vault.stability_fee_last_accrued, stacked_tokens: @vault.stacked_tokens, stacker_name: @vault.stacker_name, updated_at_block_height: @vault.updated_at_block_height } } + end + + assert_redirected_to vault_url(Vault.last) + end + + test "should show vault" do + get vault_url(@vault) + assert_response :success + end + + test "should get edit" do + get edit_vault_url(@vault) + assert_response :success + end + + test "should update vault" do + patch vault_url(@vault), params: { vault: { auction_ended: @vault.auction_ended, auto_payoff: @vault.auto_payoff, collateral: @vault.collateral, collateral_token: @vault.collateral_token, collateral_type: @vault.collateral_type, created_at_block_height: @vault.created_at_block_height, debt: @vault.debt, id: @vault.id, is_liquidated: @vault.is_liquidated, leftover_collateral: @vault.leftover_collateral, owner: @vault.owner, revoked_stacking: @vault.revoked_stacking, stability_fee_accrued: @vault.stability_fee_accrued, stability_fee_last_accrued: @vault.stability_fee_last_accrued, stacked_tokens: @vault.stacked_tokens, stacker_name: @vault.stacker_name, updated_at_block_height: @vault.updated_at_block_height } } + assert_redirected_to vault_url(@vault) + end + + test "should destroy vault" do + assert_difference("Vault.count", -1) do + delete vault_url(@vault) + end + + assert_redirected_to vaults_url + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/files/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/files/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/vaults.yml b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/vaults.yml new file mode 100644 index 0000000..45d3530 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/fixtures/vaults.yml @@ -0,0 +1,39 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + id: 1 + owner: MyString + collateral: 1 + collateral_type: MyString + collateral_token: MyString + stacked_tokens: 1 + stacker_name: MyString + revoked_stacking: false + auto_payoff: false + debt: 1 + created_at_block_height: 1 + updated_at_block_height: 1 + stability_fee_accrued: 1 + stability_fee_last_accrued: 1 + is_liquidated: false + auction_ended: false + leftover_collateral: 1 + +two: + id: 1 + owner: MyString + collateral: 1 + collateral_type: MyString + collateral_token: MyString + stacked_tokens: 1 + stacker_name: MyString + revoked_stacking: false + auto_payoff: false + debt: 1 + created_at_block_height: 1 + updated_at_block_height: 1 + stability_fee_accrued: 1 + stability_fee_last_accrued: 1 + is_liquidated: false + auction_ended: false + leftover_collateral: 1 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/helpers/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/helpers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/integration/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/integration/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/mailers/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/mailers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/vault_test.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/vault_test.rb new file mode 100644 index 0000000..c6d0629 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/models/vault_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class VaultTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/.keep b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/.keep new file mode 100644 index 0000000..e69de29 diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/vaults_test.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/vaults_test.rb new file mode 100644 index 0000000..ef35646 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/system/vaults_test.rb @@ -0,0 +1,73 @@ +require "application_system_test_case" + +class VaultsTest < ApplicationSystemTestCase + setup do + @vault = vaults(:one) + end + + test "visiting the index" do + visit vaults_url + assert_selector "h1", text: "Vaults" + end + + test "should create vault" do + visit vaults_url + click_on "New vault" + + check "Auction ended" if @vault.auction_ended + check "Auto payoff" if @vault.auto_payoff + fill_in "Collateral", with: @vault.collateral + fill_in "Collateral token", with: @vault.collateral_token + fill_in "Collateral type", with: @vault.collateral_type + fill_in "Created at block height", with: @vault.created_at_block_height + fill_in "Debt", with: @vault.debt + fill_in "Id", with: @vault.id + check "Is liquidated" if @vault.is_liquidated + fill_in "Leftover collateral", with: @vault.leftover_collateral + fill_in "Owner", with: @vault.owner + check "Revoked stacking" if @vault.revoked_stacking + fill_in "Stability fee accrued", with: @vault.stability_fee_accrued + fill_in "Stability fee last accrued", with: @vault.stability_fee_last_accrued + fill_in "Stacked tokens", with: @vault.stacked_tokens + fill_in "Stacker name", with: @vault.stacker_name + fill_in "Updated at block height", with: @vault.updated_at_block_height + click_on "Create Vault" + + assert_text "Vault was successfully created" + click_on "Back" + end + + test "should update Vault" do + visit vault_url(@vault) + click_on "Edit this vault", match: :first + + check "Auction ended" if @vault.auction_ended + check "Auto payoff" if @vault.auto_payoff + fill_in "Collateral", with: @vault.collateral + fill_in "Collateral token", with: @vault.collateral_token + fill_in "Collateral type", with: @vault.collateral_type + fill_in "Created at block height", with: @vault.created_at_block_height + fill_in "Debt", with: @vault.debt + fill_in "Id", with: @vault.id + check "Is liquidated" if @vault.is_liquidated + fill_in "Leftover collateral", with: @vault.leftover_collateral + fill_in "Owner", with: @vault.owner + check "Revoked stacking" if @vault.revoked_stacking + fill_in "Stability fee accrued", with: @vault.stability_fee_accrued + fill_in "Stability fee last accrued", with: @vault.stability_fee_last_accrued + fill_in "Stacked tokens", with: @vault.stacked_tokens + fill_in "Stacker name", with: @vault.stacker_name + fill_in "Updated at block height", with: @vault.updated_at_block_height + click_on "Update Vault" + + assert_text "Vault was successfully updated" + click_on "Back" + end + + test "should destroy Vault" do + visit vault_url(@vault) + click_on "Destroy this vault", match: :first + + assert_text "Vault was successfully destroyed" + end +end diff --git a/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/test_helper.rb b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/test_helper.rb new file mode 100644 index 0000000..d713e37 --- /dev/null +++ b/components/chainhook-cli/examples/arkadiko-data-indexing/vault-monitor/test/test_helper.rb @@ -0,0 +1,13 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +class ActiveSupport::TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/components/chainhook-cli/src/archive/mod.rs b/components/chainhook-cli/src/archive/mod.rs new file mode 100644 index 0000000..a483981 --- /dev/null +++ b/components/chainhook-cli/src/archive/mod.rs @@ -0,0 +1,85 @@ +use crate::config::Config; +use chainhook_types::StacksNetwork; +use flate2::read::GzDecoder; +use futures_util::StreamExt; +use std::fs; +use std::io::Read; +use std::io::{self, Cursor}; +use tar::Archive; + +pub fn default_tsv_file_path(network: &StacksNetwork) -> String { + format!("stacks-node-events-{:?}.tsv", network).to_lowercase() +} + +pub async fn download_tsv_file(config: &Config) -> Result<(), String> { + let destination_path = config.expected_cache_path(); + let url = config.expected_remote_tsv_url(); + let res = reqwest::get(url) + .await + .or(Err(format!("Failed to GET from '{}'", &url)))?; + + // Download chunks + let (tx, rx) = flume::bounded(0); + + let mut from = destination_path.clone(); + let decoder_thread = std::thread::spawn(move || { + let input = ChannelRead::new(rx); + let gz = GzDecoder::new(input); + let mut archive = Archive::new(gz); + archive.unpack(&destination_path).unwrap(); + }); + + if res.status() == reqwest::StatusCode::OK { + let mut stream = res.bytes_stream(); + while let Some(item) = stream.next().await { + let chunk = item + .or(Err(format!("Error while downloading file"))) + .unwrap(); + tx.send_async(chunk.to_vec()).await.unwrap(); + } + drop(tx); + } + + tokio::task::spawn_blocking(|| decoder_thread.join()) + .await + .unwrap() + .unwrap(); + + from.push("stacks-node-events.tsv"); + let mut to = from.clone(); + to.pop(); + to.push(default_tsv_file_path(&config.network.stacks_network)); + let _ = fs::rename(from, to); + + Ok(()) +} + +// Wrap a channel into something that impls `io::Read` +struct ChannelRead { + rx: flume::Receiver>, + current: Cursor>, +} + +impl ChannelRead { + fn new(rx: flume::Receiver>) -> ChannelRead { + ChannelRead { + rx, + current: Cursor::new(vec![]), + } + } +} + +impl Read for ChannelRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.current.position() == self.current.get_ref().len() as u64 { + // We've exhausted the previous chunk, get a new one. + if let Ok(vec) = self.rx.recv() { + self.current = io::Cursor::new(vec); + } + // If recv() "fails", it means the sender closed its part of + // the channel, which means EOF. Propagate EOF by allowing + // a read from the exhausted cursor. + } + self.current.read(buf) + } +} diff --git a/components/chainhook-cli/src/block/digestion.rs b/components/chainhook-cli/src/block/digestion.rs new file mode 100644 index 0000000..fbfa722 --- /dev/null +++ b/components/chainhook-cli/src/block/digestion.rs @@ -0,0 +1,147 @@ +use super::DigestingCommand; +use crate::config::Config; +use chainhook_event_observer::indexer; +use chainhook_event_observer::indexer::Indexer; +use chainhook_event_observer::utils::Context; +use redis::Commands; +use std::cmp::Ordering; +use std::{collections::BinaryHeap, process, sync::mpsc::Receiver}; + +const JOB_TERMINATION_HIGH_PRIORITY: u64 = 100_000_000; +const JOB_DIGEST_BLOCK_SEED_PRIORITY: u64 = 100_000; +const JOB_LOW_PRIORITY: u64 = 10; +const JOB_TERMINATION_LOW_PRIORITY: u64 = 1; + +#[derive(Debug, Clone, Eq, PartialEq)] +struct Job { + pub command: DigestingCommand, + pub priority: u64, +} + +pub fn start( + command_rx: Receiver, + config: &Config, + ctx: &Context, +) -> Result<(), String> { + // let mut bit_vector + let mut job_queue: BinaryHeap = BinaryHeap::new(); + let redis_config = config.expected_redis_config(); + let client = redis::Client::open(redis_config.uri.clone()).unwrap(); + let mut indexer = Indexer::new(config.network.clone()); + + let mut con = match client.get_connection() { + Ok(con) => con, + Err(message) => { + return Err(format!("Redis: {}", message.to_string())); + } + }; + let mut block_digested = 0; + loop { + while let Some(job) = job_queue.pop() { + match &job.command { + DigestingCommand::DigestSeedBlock(block_identifier) => { + let key = format!("stx:{}", block_identifier.index); + let payload: String = con + .hget(&key, "blob") + .expect("unable to retrieve tip height"); + let block_data = match indexer::stacks::standardize_stacks_serialized_block( + &indexer.config, + &payload, + &mut indexer.stacks_context, + ctx, + ) { + Ok(block) => block, + Err(e) => { + error!(&ctx.expect_logger(), "{e}"); + continue; + } + }; + let _: Result<(), redis::RedisError> = con.hset_multiple( + &key, + &[ + ("transactions", json!(block_data.transactions).to_string()), + ("metadata", json!(block_data.metadata).to_string()), + ("timestamp", json!(block_data.timestamp).to_string()), + ], + ); + if block_digested > 0 && job_queue.is_empty() { + info!( + ctx.expect_logger(), + "Seeding completed - {} block processed", + block_digested + 1 + ); + } + block_digested += 1; + } + DigestingCommand::GarbageCollect => { + let keys_to_prune: Vec = con + .scan_match("stx:*:*") + .expect("unable to retrieve prunable entries") + .into_iter() + .collect(); + let _: Result<(), redis::RedisError> = con.del(&keys_to_prune); + debug!( + ctx.expect_logger(), + "{} Stacks orphaned blocks removed from storage", + keys_to_prune.len() + ); + info!( + ctx.expect_logger(), + "Initial ingestion succesfully performed" + ) + } + DigestingCommand::Terminate | DigestingCommand::Kill => { + info!(ctx.expect_logger(), "Terminating"); + return Ok(()); + } + } + while let Ok(new_command) = command_rx.try_recv() { + job_queue.push(new_job(new_command)); + } + } + let command = match command_rx.recv() { + Ok(command) => command, + Err(e) => { + error!( + ctx.expect_logger(), + "block digestion channel broken {:?}", e + ); + process::exit(1); + } + }; + job_queue.push(new_job(command)); + } +} + +fn new_job(command: DigestingCommand) -> Job { + match command { + DigestingCommand::DigestSeedBlock(block_identifier) => Job { + priority: JOB_DIGEST_BLOCK_SEED_PRIORITY + block_identifier.index, + command: DigestingCommand::DigestSeedBlock(block_identifier), + }, + DigestingCommand::GarbageCollect => Job { + priority: JOB_LOW_PRIORITY, + command: DigestingCommand::GarbageCollect, + }, + DigestingCommand::Terminate => Job { + priority: JOB_TERMINATION_LOW_PRIORITY, + command: DigestingCommand::Terminate, + }, + DigestingCommand::Kill => Job { + priority: JOB_TERMINATION_HIGH_PRIORITY, + command: DigestingCommand::Kill, + }, + } +} + +impl Ord for Job { + fn cmp(&self, other: &Job) -> Ordering { + self.priority.cmp(&other.priority) + } +} + +impl PartialOrd for Job { + fn partial_cmp(&self, other: &Job) -> Option { + Some(self.cmp(other)) + } +} diff --git a/components/chainhook-cli/src/block/ingestion.rs b/components/chainhook-cli/src/block/ingestion.rs new file mode 100644 index 0000000..f45de40 --- /dev/null +++ b/components/chainhook-cli/src/block/ingestion.rs @@ -0,0 +1,234 @@ +use crate::config::Config; +use chainhook_event_observer::indexer::{self, Indexer}; +use chainhook_event_observer::utils::Context; +use chainhook_types::BlockIdentifier; +use redis::Commands; +use serde::Deserialize; +use std::sync::mpsc::Sender; +use std::{sync::mpsc::channel, thread}; + +use super::DigestingCommand; + +#[derive(Debug, Deserialize)] +pub struct Record { + pub id: u64, + pub created_at: String, + pub kind: RecordKind, + pub raw_log: String, +} + +#[derive(Debug, Deserialize)] +pub enum RecordKind { + #[serde(rename = "/new_block")] + StacksBlockReceived, + #[serde(rename = "/new_microblocks")] + StacksMicroblockReceived, + #[serde(rename = "/new_burn_block")] + BitcoinBlockReceived, + #[serde(rename = "/new_mempool_tx")] + TransactionAdmitted, + #[serde(rename = "/drop_mempool_tx")] + TransactionDropped, + #[serde(rename = "/attachments/new")] + AttachmentReceived, +} + +pub fn start( + digestion_tx: Sender, + config: &Config, + ctx: Context, +) -> Result<(BlockIdentifier, BlockIdentifier), String> { + let (stacks_record_tx, stacks_record_rx) = channel(); + let (bitcoin_record_tx, bitcoin_record_rx) = channel(); + + let seed_tsv_path = config.expected_local_tsv_file().clone(); + info!( + ctx.expect_logger(), + "Initialize storage with events {}", + seed_tsv_path.display() + ); + let parsing_handle = thread::spawn(move || { + let mut reader_builder = csv::ReaderBuilder::default() + .has_headers(false) + .delimiter(b'\t') + .buffer_capacity(8 * (1 << 10)) + .from_path(&seed_tsv_path) + .expect("unable to create csv reader"); + + // TODO + // let mut record = csv::StringRecord::new(); + // let mut rdr = Reader::from_reader(data.as_bytes()); + // let mut record = StringRecord::new(); + // if rdr.read_record(&mut record)? { + // assert_eq!(record, vec!["Boston", "United States", "4628910"]); + // Ok(()) + // } else { + // Err(From::from("expected at least one record but got none")) + // } + + for result in reader_builder.deserialize() { + // Notice that we need to provide a type hint for automatic + // deserialization. + let record: Record = result.unwrap(); + match &record.kind { + RecordKind::BitcoinBlockReceived => { + let _ = bitcoin_record_tx.send(Some(record)); + } + RecordKind::StacksBlockReceived => { + let _ = stacks_record_tx.send(Some(record)); + } + // RecordKind::StacksMicroblockReceived => { + // let _ = stacks_record_tx.send(Some(record)); + // }, + _ => {} + }; + } + let _ = stacks_record_tx.send(None); + let _ = bitcoin_record_tx.send(None); + }); + + let stacks_thread_config = config.clone(); + + let stacks_processing_handle = thread::spawn(move || { + let redis_config = stacks_thread_config.expected_redis_config(); + + let client = redis::Client::open(redis_config.uri.clone()).unwrap(); + let mut con = match client.get_connection() { + Ok(con) => con, + Err(message) => { + return Err(format!("Redis: {}", message.to_string())); + } + }; + let _indexer = Indexer::new(stacks_thread_config.network.clone()); + + // Retrieve the former highest block height stored + let former_tip_height: u64 = con.get(&format!("stx:tip")).unwrap_or(0); + + let mut tip = 0; + + while let Ok(Some(record)) = stacks_record_rx.recv() { + let (block_identifier, parent_block_identifier) = match &record.kind { + RecordKind::StacksBlockReceived => { + match indexer::stacks::standardize_stacks_serialized_block_header( + &record.raw_log, + ) { + Ok(data) => data, + Err(e) => { + error!(ctx.expect_logger(), "{e}"); + continue; + } + } + } + _ => unreachable!(), + }; + + let _: Result<(), redis::RedisError> = con.hset_multiple( + &format!("stx:{}:{}", block_identifier.index, block_identifier.hash), + &[ + ("block_identifier", json!(block_identifier).to_string()), + ( + "parent_block_identifier", + json!(parent_block_identifier).to_string(), + ), + ("blob", record.raw_log), + ], + ); + if block_identifier.index > tip { + tip = block_identifier.index; + let _: Result<(), redis::RedisError> = con.set(&format!("stx:tip"), tip); + } + } + + // Retrieve highest block height stored + let tip_height: u64 = con + .get(&format!("stx:tip")) + .expect("unable to retrieve tip height"); + + if former_tip_height == tip_height { + // No new block to ingest, we will make sure that we have all the blocks, + // and succesfully terminate this routine. + let _ = digestion_tx.send(DigestingCommand::GarbageCollect); + // Retrieve block identifier + let key = format!("stx:{}", tip_height); + let block_identifier: BlockIdentifier = { + let payload: String = con + .hget(&key, "block_identifier") + .expect("unable to retrieve tip height"); + serde_json::from_str(&payload).unwrap() + }; + info!( + ctx.expect_logger(), + "Local storage seeded, no new block to process" + ); + return Ok(block_identifier); + } + + let chain_tips: Vec = con + .scan_match(&format!("stx:{}:*", tip_height)) + .expect("unable to retrieve tip height") + .into_iter() + .collect(); + + info!( + ctx.expect_logger(), + "Start processing canonical Stacks blocks from chain tip #{}", tip_height + ); + // Retrieve all the headers stored at this height (SCAN - expensive) + let mut selected_tip = BlockIdentifier::default(); + for key in chain_tips.into_iter() { + let payload: String = con + .hget(&key, "block_identifier") + .expect("unable to retrieve tip height"); + selected_tip = serde_json::from_str(&payload).unwrap(); + break; + } + + let mut cursor = selected_tip.clone(); + while cursor.index > 0 { + let key = format!("stx:{}:{}", cursor.index, cursor.hash); + let parent_block_identifier: BlockIdentifier = { + let payload: String = con + .hget(&key, "parent_block_identifier") + .expect("unable to retrieve tip height"); + serde_json::from_str(&payload).unwrap() + }; + let _: Result<(), redis::RedisError> = con.rename(key, format!("stx:{}", cursor.index)); + let _ = digestion_tx.send(DigestingCommand::DigestSeedBlock(cursor.clone())); + cursor = parent_block_identifier.clone(); + } + info!( + ctx.expect_logger(), + "{} Stacks blocks queued for processing", tip_height + ); + + let _ = digestion_tx.send(DigestingCommand::GarbageCollect); + Ok(selected_tip) + }); + + let bitcoin_indexer_config = config.clone(); + + let bitcoin_processing_handle = thread::spawn(move || { + let redis_config = bitcoin_indexer_config.expected_redis_config(); + + let client = redis::Client::open(redis_config.uri.clone()).unwrap(); + let mut con = match client.get_connection() { + Ok(con) => con, + Err(message) => { + return Err(format!("Redis: {}", message.to_string())); + } + }; + while let Ok(Some(record)) = bitcoin_record_rx.recv() { + let _: () = match con.set(&format!("btc:{}", record.id), record.raw_log.as_str()) { + Ok(()) => (), + Err(e) => return Err(e.to_string()), + }; + } + Ok(BlockIdentifier::default()) + }); + + let _ = parsing_handle.join(); + let stacks_chain_tip = stacks_processing_handle.join().unwrap()?; + let bitcoin_chain_tip = bitcoin_processing_handle.join().unwrap()?; + + Ok((stacks_chain_tip, bitcoin_chain_tip)) +} diff --git a/components/chainhook-cli/src/block/mod.rs b/components/chainhook-cli/src/block/mod.rs new file mode 100644 index 0000000..94f6a8c --- /dev/null +++ b/components/chainhook-cli/src/block/mod.rs @@ -0,0 +1,11 @@ +pub mod digestion; +pub mod ingestion; +use chainhook_types::BlockIdentifier; + +#[derive(Debug, Clone, Eq, PartialEq)] +pub enum DigestingCommand { + DigestSeedBlock(BlockIdentifier), + GarbageCollect, + Kill, + Terminate, +} diff --git a/components/chainhook-cli/src/cli/mod.rs b/components/chainhook-cli/src/cli/mod.rs new file mode 100644 index 0000000..7b67beb --- /dev/null +++ b/components/chainhook-cli/src/cli/mod.rs @@ -0,0 +1,1182 @@ +use super::block; +use crate::archive; +use crate::block::DigestingCommand; +use crate::config::Config; + +use chainhook_event_observer::chainhooks::bitcoin::{ + handle_bitcoin_hook_action, BitcoinChainhookOccurrence, BitcoinTriggerChainhook, +}; +use chainhook_event_observer::chainhooks::types::ChainhookConfig; +use chainhook_event_observer::indexer::bitcoin::standardize_bitcoin_block; +use chainhook_event_observer::observer::{ + start_event_observer, EventObserverConfig, ObserverCommand, ObserverEvent, +}; +use chainhook_event_observer::utils::Context; +use chainhook_event_observer::{ + chainhooks::stacks::{ + evaluate_stacks_transaction_predicate_on_transaction, handle_stacks_hook_action, + StacksChainhookOccurrence, StacksTriggerChainhook, + }, + chainhooks::types::ChainhookSpecification, +}; + +use bitcoincore_rpc::{Auth, Client, RpcApi}; +use chainhook_types::{ + BitcoinBlockData, BitcoinBlockMetadata, BitcoinNetwork, BitcoinTransactionData, + BlockIdentifier, StacksBlockData, StacksBlockMetadata, StacksChainEvent, StacksNetwork, + StacksTransactionData, +}; +use clap::{Parser, Subcommand}; +use ctrlc; +use hiro_system_kit; +use redis::{Commands, Connection}; +use reqwest::Url; +use std::collections::HashSet; +use std::sync::mpsc::Sender; +use std::{collections::HashMap, process, sync::mpsc::channel, thread}; + +pub const DEFAULT_INGESTION_PORT: u16 = 20455; +pub const DEFAULT_CONTROL_PORT: u16 = 20456; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Opts { + #[clap(subcommand)] + command: Command, +} + +#[derive(Subcommand, PartialEq, Clone, Debug)] +enum Command { + /// Start chainhook-cli + #[clap(subcommand)] + Node(NodeCommand), + /// Start chainhook-cli in replay mode + #[clap(name = "replay", bin_name = "replay")] + Replay(ReplayCommand), + /// Scan blocks (one-off) from specified network and apply provided predicate + #[clap(name = "scan", bin_name = "scan")] + Scan(ScanCommand), +} + +#[derive(Subcommand, PartialEq, Clone, Debug)] +enum NodeCommand { + /// Start chainhook-cli + #[clap(name = "start", bin_name = "start")] + Start(StartCommand), +} + +#[derive(Parser, PartialEq, Clone, Debug)] +struct StartCommand { + /// Target Devnet network + #[clap( + long = "devnet", + conflicts_with = "testnet", + conflicts_with = "mainnet" + )] + pub devnet: bool, + /// Target Testnet network + #[clap( + long = "testnet", + conflicts_with = "devnet", + conflicts_with = "mainnet" + )] + pub testnet: bool, + /// Target Mainnet network + #[clap( + long = "mainnet", + conflicts_with = "testnet", + conflicts_with = "devnet" + )] + pub mainnet: bool, + /// Load config file path + #[clap( + long = "config-path", + conflicts_with = "mainnet", + conflicts_with = "testnet", + conflicts_with = "devnet" + )] + pub config_path: Option, +} + +#[derive(Parser, PartialEq, Clone, Debug)] +struct ReplayCommand { + pub devnet: bool, + /// Target Testnet network + #[clap( + long = "testnet", + conflicts_with = "devnet", + conflicts_with = "mainnet" + )] + pub testnet: bool, + /// Target Mainnet network + #[clap( + long = "mainnet", + conflicts_with = "testnet", + conflicts_with = "devnet" + )] + pub mainnet: bool, + /// Load config file path + #[clap( + long = "config-path", + conflicts_with = "mainnet", + conflicts_with = "testnet", + conflicts_with = "devnet" + )] + pub config_path: Option, + /// Apply chainhook action (false by default) + #[clap(long = "apply-trigger")] + pub apply_trigger: bool, + /// Bitcoind node url override + #[clap(long = "bitcoind-rpc-url")] + pub bitcoind_rpc_url: Option, +} + +#[derive(Parser, PartialEq, Clone, Debug)] +struct ScanCommand { + pub devnet: bool, + /// Target Testnet network + #[clap( + long = "testnet", + conflicts_with = "devnet", + conflicts_with = "mainnet" + )] + pub testnet: bool, + /// Target Mainnet network + #[clap( + long = "mainnet", + conflicts_with = "testnet", + conflicts_with = "devnet" + )] + pub mainnet: bool, + /// Load config file path + #[clap( + long = "config-path", + conflicts_with = "mainnet", + conflicts_with = "testnet", + conflicts_with = "devnet" + )] + pub config_path: Option, + /// Load chainhook file path (yaml format) + #[clap( + long = "chainhook-spec-path", + short = 'p' + )] + pub chainhook_spec_path: String, +} + +pub fn main() { + let logger = hiro_system_kit::log::setup_logger(); + let _guard = hiro_system_kit::log::setup_global_logger(logger.clone()); + let ctx = Context { + logger: Some(logger), + tracer: false, + }; + + let opts: Opts = match Opts::try_parse() { + Ok(opts) => opts, + Err(e) => { + println!("{}", e); + process::exit(1); + } + }; + + match opts.command { + Command::Node(subcmd) => match subcmd { + NodeCommand::Start(cmd) => { + let config = + match Config::default(cmd.devnet, cmd.testnet, cmd.mainnet, &cmd.config_path) { + Ok(config) => config, + Err(e) => { + println!("{e}"); + process::exit(1); + } + }; + start_node(config, ctx); + } + }, + Command::Replay(cmd) => { + let mut config = + match Config::default(cmd.devnet, cmd.testnet, cmd.mainnet, &cmd.config_path) { + Ok(config) => config, + Err(e) => { + println!("{e}"); + process::exit(1); + } + }; + if let Some(bitcoind_rpc_url) = cmd.bitcoind_rpc_url { + let url = match Url::parse(&bitcoind_rpc_url) { + Ok(url) => url, + Err(e) => { + println!("{e}"); + process::exit(1); + } + }; + let host = url + .host() + .expect("unable to retrieve host from bitcoind_rpc_url") + .to_string(); + let port = url + .port() + .expect("unable to retrieve port from bitcoind_rpc_url") + .to_string(); + let username = url.username().to_string(); + let password = url + .password() + .expect("unable to retrieve password from bitcoind_rpc_url") + .to_string(); + config.network.bitcoin_node_rpc_url = format!("http://{}:{}", host, port); + config.network.bitcoin_node_rpc_username = username; + config.network.bitcoin_node_rpc_password = password; + } + start_replay(config, cmd.apply_trigger, ctx); + } + Command::Scan(cmd) => { + let config = + match Config::default(cmd.devnet, cmd.testnet, cmd.mainnet, &cmd.config_path) { + Ok(config) => config, + Err(e) => { + println!("{e}"); + process::exit(1); + } + }; + start_scan(config, ctx); + } + } +} + + +pub fn install_ctrlc_handler(terminate_tx: Sender, ctx: Context) { + ctrlc::set_handler(move || { + warn!( + &ctx.expect_logger(), + "Manual interruption signal received" + ); + terminate_tx + .send(DigestingCommand::Kill) + .expect("Unable to terminate service"); + }).expect("Error setting Ctrl-C handler"); +} + + +pub fn download_dataset_if_required(config: &mut Config, ctx: &Context) -> bool { + if config.is_initial_ingestion_required() { + // Download default tsv. + if config.rely_on_remote_tsv() && config.should_download_remote_tsv() { + let url = config.expected_remote_tsv_url(); + let mut destination_path = config.expected_cache_path(); + destination_path.push(archive::default_tsv_file_path(&config.network.stacks_network)); + // Download archive if not already present in cache + if !destination_path.exists() { + info!(ctx.expect_logger(), "Downloading {}", url); + match hiro_system_kit::nestable_block_on(archive::download_tsv_file(&config)) { + Ok(_) => {} + Err(e) => { + error!(ctx.expect_logger(), "{}", e); + process::exit(1); + } + } + } + config.add_local_tsv_source(&destination_path); + } + true + } else { + info!( + ctx.expect_logger(), + "Streaming blocks from stacks-node {}", + config.expected_stacks_node_event_source() + ); + false + } +} + +pub fn start_scan(mut config: Config, ctx: Context) { + let (digestion_tx, digestion_rx) = channel(); + install_ctrlc_handler(digestion_tx.clone(), ctx.clone()); + let data_downloaded = download_dataset_if_required(&mut config, &ctx); + if !data_downloaded { + error!(ctx.expect_logger(), "No dataset to scan"); + process::exit(1); + } + + info!(ctx.expect_logger(), "Scanning..."); +} + +pub fn start_replay(mut config: Config, apply: bool, ctx: Context) { + let indexer_config = config.network.clone(); + + let (digestion_tx, digestion_rx) = channel(); + let (observer_event_tx, observer_event_rx) = crossbeam_channel::unbounded(); + let (observer_command_tx, observer_command_rx) = channel(); + + let terminate_digestion_tx = digestion_tx.clone(); + let context_cloned = ctx.clone(); + ctrlc::set_handler(move || { + warn!( + &context_cloned.expect_logger(), + "Manual interruption signal received" + ); + terminate_digestion_tx + .send(DigestingCommand::Kill) + .expect("Unable to terminate service"); + }) + .expect("Error setting Ctrl-C handler"); + + if config.is_initial_ingestion_required() { + // Download default tsv. + if config.rely_on_remote_tsv() && config.should_download_remote_tsv() { + let url = config.expected_remote_tsv_url(); + let mut destination_path = config.expected_cache_path(); + destination_path.push("stacks-node-events.tsv"); + // Download archive if not already present in cache + if !destination_path.exists() { + info!(ctx.expect_logger(), "Downloading {}", url); + match hiro_system_kit::nestable_block_on(archive::download_tsv_file(&config)) { + Ok(_) => {} + Err(e) => { + error!(ctx.expect_logger(), "{}", e); + process::exit(1); + } + } + let mut destination_path = config.expected_cache_path(); + destination_path.push("stacks-node-events.tsv"); + } + config.add_local_tsv_source(&destination_path); + + let ingestion_config = config.clone(); + let seed_digestion_tx = digestion_tx.clone(); + let context_cloned = ctx.clone(); + + thread::spawn(move || { + let res = block::ingestion::start( + seed_digestion_tx.clone(), + &ingestion_config, + context_cloned.clone(), + ); + let (_stacks_chain_tip, _bitcoin_chain_tip) = match res { + Ok(chain_tips) => chain_tips, + Err(e) => { + error!(&context_cloned.expect_logger(), "{}", e); + process::exit(1); + } + }; + }); + } + } else { + info!( + ctx.expect_logger(), + "Streaming blocks from stacks-node {}", + config.expected_stacks_node_event_source() + ); + } + + let digestion_config = config.clone(); + let terminate_observer_command_tx = observer_command_tx.clone(); + let context_cloned = ctx.clone(); + + thread::spawn(move || { + let res = block::digestion::start(digestion_rx, &digestion_config, &context_cloned); + if let Err(e) = res { + crit!(&context_cloned.expect_logger(), "{}", e); + } + let _ = terminate_observer_command_tx.send(ObserverCommand::Terminate); + }); + + let event_observer_config = EventObserverConfig { + normalization_enabled: true, + grpc_server_enabled: false, + hooks_enabled: true, + bitcoin_rpc_proxy_enabled: true, + event_handlers: vec![], + chainhook_config: None, + ingestion_port: DEFAULT_INGESTION_PORT, + control_port: DEFAULT_CONTROL_PORT, + bitcoin_node_username: config.network.bitcoin_node_rpc_username.clone(), + bitcoin_node_password: config.network.bitcoin_node_rpc_password.clone(), + bitcoin_node_rpc_url: config.network.bitcoin_node_rpc_url.clone(), + stacks_node_rpc_url: config.network.stacks_node_rpc_url.clone(), + operators: HashSet::new(), + display_logs: false, + }; + info!( + ctx.expect_logger(), + "Listening for new blockchain events on port {}", DEFAULT_INGESTION_PORT + ); + info!( + ctx.expect_logger(), + "Listening for chainhook predicate registrations on port {}", DEFAULT_CONTROL_PORT + ); + let context_cloned = ctx.clone(); + + let _ = std::thread::spawn(move || { + let future = start_event_observer( + event_observer_config, + observer_command_tx, + observer_command_rx, + Some(observer_event_tx), + context_cloned, + ); + let _ = hiro_system_kit::nestable_block_on(future); + }); + + let redis_config = config.expected_redis_config(); + let client = redis::Client::open(redis_config.uri.clone()).unwrap(); + let mut redis_con = match client.get_connection() { + Ok(con) => con, + Err(message) => { + crit!(ctx.expect_logger(), "Redis: {}", message.to_string()); + panic!(); + } + }; + + let auth = Auth::UserPass( + config.network.bitcoin_node_rpc_username.clone(), + config.network.bitcoin_node_rpc_password.clone(), + ); + + let bitcoin_rpc = match Client::new(&config.network.bitcoin_node_rpc_url, auth) { + Ok(con) => con, + Err(message) => { + crit!(ctx.expect_logger(), "Bitcoin RPC: {}", message.to_string()); + panic!(); + } + }; + + loop { + let event = match observer_event_rx.recv() { + Ok(cmd) => cmd, + Err(e) => { + crit!( + ctx.expect_logger(), + "Error: broken channel {}", + e.to_string() + ); + break; + } + }; + match event { + ObserverEvent::HookRegistered(chainhook) => { + // If start block specified, use it. + // I no start block specified, depending on the nature the hook, we'd like to retrieve: + // - contract-id + + match chainhook { + ChainhookSpecification::Stacks(stacks_hook) => { + // Retrieve highest block height stored + let tip_height: u64 = redis_con + .get(&format!("stx:tip")) + .expect("unable to retrieve tip height"); + + let start_block = stacks_hook.start_block.unwrap_or(2); // TODO(lgalabru): handle STX hooks and genesis block :s + let end_block = stacks_hook.end_block.unwrap_or(tip_height); // TODO(lgalabru): handle STX hooks and genesis block :s + + info!( + ctx.expect_logger(), "Processing Stacks chainhook {}, will scan blocks [{}; {}] (apply = {})", + stacks_hook.uuid, start_block, end_block, apply + ); + let mut total_hits = vec![]; + for cursor in start_block..=end_block { + debug!( + ctx.expect_logger(), + "Evaluating predicate #{} on block #{}", stacks_hook.uuid, cursor + ); + let ( + block_identifier, + parent_block_identifier, + timestamp, + transactions, + metadata, + ) = { + let payload: Vec = redis_con + .hget( + &format!("stx:{}", cursor), + &[ + "block_identifier", + "parent_block_identifier", + "timestamp", + "transactions", + "metadata", + ], + ) + .expect("unable to retrieve tip height"); + if payload.len() != 5 { + warn!( + ctx.expect_logger(), + "Unable to retrieve full data for block #{}", cursor + ); + continue; + } + ( + serde_json::from_str::(&payload[0]).unwrap(), + serde_json::from_str::(&payload[1]).unwrap(), + serde_json::from_str::(&payload[2]).unwrap(), + serde_json::from_str::>(&payload[3]) + .unwrap(), + serde_json::from_str::(&payload[4]) + .unwrap(), + ) + }; + let mut hits = vec![]; + for tx in transactions.iter() { + if evaluate_stacks_transaction_predicate_on_transaction( + &tx, + &stacks_hook, + &ctx, + ) { + debug!( + ctx.expect_logger(), + "Action #{} triggered by transaction {} (block #{})", + stacks_hook.uuid, + tx.transaction_identifier.hash, + cursor + ); + hits.push(tx); + total_hits.push(tx.transaction_identifier.hash.to_string()); + } + } + + if hits.len() > 0 { + let block = StacksBlockData { + block_identifier, + parent_block_identifier, + timestamp, + transactions: vec![], + metadata, + }; + let trigger = StacksTriggerChainhook { + chainhook: &stacks_hook, + apply: vec![(hits, &block)], + rollback: vec![], + }; + + let proofs = HashMap::new(); + if apply { + if let Some(result) = + handle_stacks_hook_action(trigger, &proofs, &ctx) + { + if let StacksChainhookOccurrence::Http(request) = result { + hiro_system_kit::nestable_block_on(request.send()) + .unwrap(); + } + } + } + } + } + + info!(ctx.expect_logger(), "Stacks chainhook {} scan completed and triggered by {} transactions {}", stacks_hook.uuid, total_hits.len(), total_hits.join(",")) + } + ChainhookSpecification::Bitcoin(bitcoin_hook) => { + let start_block = match bitcoin_hook.start_block { + Some(start_block) => start_block, + None => { + warn!(ctx.expect_logger(), "Bitcoin chainhook specification must include a field start_block in replay mode"); + continue; + } + }; + let tip_height = match bitcoin_rpc.get_blockchain_info() { + Ok(result) => result.blocks, + Err(e) => { + warn!( + ctx.expect_logger(), + "unable to retrieve Bitcoin chain tip ({})", + e.to_string() + ); + continue; + } + }; + let end_block = bitcoin_hook.end_block.unwrap_or(tip_height); + + info!( + ctx.expect_logger(), "Processing Bitcoin chainhook {}, will scan blocks [{}; {}] (apply = {})", + bitcoin_hook.uuid, start_block, end_block, apply + ); + + let mut total_hits = vec![]; + for cursor in start_block..=end_block { + debug!( + ctx.expect_logger(), + "Evaluating predicate #{} on block #{}", bitcoin_hook.uuid, cursor + ); + + // Try to retrieve block from cache + + let cached_block = { + let payload: Vec = redis_con + .hget( + &format!("btc:{}", cursor), + &[ + "block_identifier", + "parent_block_identifier", + "timestamp", + "transactions", + "metadata", + ], + ) + .expect("unable to retrieve tip height"); + if payload.len() != 5 { + None + } else { + let block = BitcoinBlockData { + block_identifier: serde_json::from_str::( + &payload[0], + ) + .unwrap(), + parent_block_identifier: serde_json::from_str::< + BlockIdentifier, + >( + &payload[1] + ) + .unwrap(), + timestamp: serde_json::from_str::(&payload[2]) + .unwrap(), + transactions: serde_json::from_str::< + Vec, + >( + &payload[3] + ) + .unwrap(), + metadata: serde_json::from_str::( + &payload[4], + ) + .unwrap(), + }; + debug!( + ctx.expect_logger(), + "Bitcoin block #{} retrieved from cache", + block.block_identifier.index + ); + Some(block) + } + }; + + let block = match cached_block { + Some(block) => block, + None => { + let block_hash = match bitcoin_rpc.get_block_hash(cursor) { + Ok(block_hash) => block_hash, + Err(e) => { + error!( + ctx.expect_logger(), + "unable to retrieve block hash {}: {}", + cursor, + e.to_string() + ); + continue; + } + }; + + let block = match bitcoin_rpc.get_block(&block_hash) { + Ok(block) => { + standardize_bitcoin_block( + &indexer_config, + cursor, + block, + &ctx, + ) + .unwrap() // todo + } + Err(e) => { + error!( + ctx.expect_logger(), + "unable to retrieve block {}: {}", + cursor, + e.to_string() + ); + continue; + } + }; + + let key = format!("btc:{}", block.block_identifier.index); + match redis_con.hset_multiple( + &key, + &[ + ( + "block_identifier", + json!(block.block_identifier).to_string(), + ), + ( + "parent_block_identifier", + json!(block.parent_block_identifier).to_string(), + ), + ("transactions", json!(block.transactions).to_string()), + ("metadata", json!(block.metadata).to_string()), + ("timestamp", json!(block.timestamp).to_string()), + ], + ) { + Ok(()) => { + debug!( + ctx.expect_logger(), + "Bitcoin block #{} saved to cache", + block.block_identifier.index + ); + } + Err(e) => { + warn!( + ctx.expect_logger(), + "unable to keep block {key} in cache: {}", + e.to_string() + ); + } + }; + + block + } + }; + + let mut hits = vec![]; + for tx in block.transactions.iter() { + if bitcoin_hook.evaluate_transaction_predicate(&tx) { + debug!( + ctx.expect_logger(), + "Action #{} triggered by transaction {} (block #{})", + bitcoin_hook.uuid, + tx.transaction_identifier.hash, + cursor + ); + hits.push(tx); + total_hits.push(tx.transaction_identifier.hash.to_string()); + } + } + + if hits.len() > 0 { + let trigger = BitcoinTriggerChainhook { + chainhook: &bitcoin_hook, + apply: vec![(hits, &block)], + rollback: vec![], + }; + + let proofs = HashMap::new(); + if apply { + if let Some(result) = + handle_bitcoin_hook_action(trigger, &proofs) + { + if let BitcoinChainhookOccurrence::Http(request) = result { + hiro_system_kit::nestable_block_on(request.send()) + .unwrap(); + } + } + } + } + } + info!(ctx.expect_logger(), "Bitcoin chainhook {} scan completed and triggered by {} transactions {}", bitcoin_hook.uuid, total_hits.len(), total_hits.join(",")) + } + } + } + ObserverEvent::BitcoinChainEvent(_chain_update) => { + debug!(ctx.expect_logger(), "Bitcoin update not stored"); + } + ObserverEvent::StacksChainEvent(chain_event) => { + match &chain_event { + StacksChainEvent::ChainUpdatedWithBlocks(data) => { + update_storage_with_confirmed_stacks_blocks( + &mut redis_con, + &data.confirmed_blocks, + &ctx, + ); + } + StacksChainEvent::ChainUpdatedWithReorg(data) => { + update_storage_with_confirmed_stacks_blocks( + &mut redis_con, + &data.confirmed_blocks, + &ctx, + ); + } + StacksChainEvent::ChainUpdatedWithMicroblocks(_) + | StacksChainEvent::ChainUpdatedWithMicroblocksReorg(_) => {} + }; + } + ObserverEvent::Terminate => { + break; + } + _ => {} + } + } +} + +pub fn seed_storage() {} + +pub fn start_node(mut config: Config, ctx: Context) { + let (digestion_tx, digestion_rx) = channel(); + let (observer_event_tx, observer_event_rx) = crossbeam_channel::unbounded(); + let (observer_command_tx, observer_command_rx) = channel(); + + let terminate_digestion_tx = digestion_tx.clone(); + let context_cloned = ctx.clone(); + ctrlc::set_handler(move || { + warn!( + &context_cloned.expect_logger(), + "Manual interruption signal received" + ); + terminate_digestion_tx + .send(DigestingCommand::Kill) + .expect("Unable to terminate service"); + }) + .expect("Error setting Ctrl-C handler"); + + if config.is_initial_ingestion_required() { + // Download default tsv. + if config.rely_on_remote_tsv() && config.should_download_remote_tsv() { + let url = config.expected_remote_tsv_url(); + let mut destination_path = config.expected_cache_path(); + destination_path.push("stacks-node-events.tsv"); + // Download archive if not already present in cache + if !destination_path.exists() { + info!(ctx.expect_logger(), "Downloading {}", url); + match hiro_system_kit::nestable_block_on(archive::download_tsv_file(&config)) { + Ok(_) => {} + Err(e) => { + error!(ctx.expect_logger(), "{}", e); + process::exit(1); + } + } + let mut destination_path = config.expected_cache_path(); + destination_path.push("stacks-node-events.tsv"); + } + config.add_local_tsv_source(&destination_path); + + let ingestion_config = config.clone(); + let seed_digestion_tx = digestion_tx.clone(); + let context_cloned = ctx.clone(); + + thread::spawn(move || { + let res = block::ingestion::start( + seed_digestion_tx.clone(), + &ingestion_config, + context_cloned.clone(), + ); + let (_stacks_chain_tip, _bitcoin_chain_tip) = match res { + Ok(chain_tips) => chain_tips, + Err(e) => { + error!(&context_cloned.expect_logger(), "{}", e); + process::exit(1); + } + }; + }); + } + } else { + info!( + ctx.expect_logger(), + "Streaming blocks from stacks-node {}", + config.expected_stacks_node_event_source() + ); + } + + let digestion_config = config.clone(); + let terminate_observer_command_tx = observer_command_tx.clone(); + let context_cloned = ctx.clone(); + + thread::spawn(move || { + let res = block::digestion::start(digestion_rx, &digestion_config, &context_cloned); + if let Err(e) = res { + error!(&context_cloned.expect_logger(), "{}", e); + } + let _ = terminate_observer_command_tx.send(ObserverCommand::Terminate); + }); + + let mut chainhook_config = ChainhookConfig::new(); + + { + let redis_config = config.expected_redis_config(); + let client = redis::Client::open(redis_config.uri.clone()).unwrap(); + let mut redis_con = match client.get_connection() { + Ok(con) => con, + Err(message) => { + error!(ctx.expect_logger(), "Redis: {}", message.to_string()); + panic!(); + } + }; + + let chainhooks_to_load: Vec = redis_con + .scan_match("chainhook:*:*:*") + .expect("unable to retrieve prunable entries") + .into_iter() + .collect(); + + for key in chainhooks_to_load.iter() { + let chainhook = match redis_con.hget::<_, _, String>(key, "specification") { + Ok(spec) => { + ChainhookSpecification::deserialize_specification(&spec, key).unwrap() + // todo + } + Err(e) => { + error!( + ctx.expect_logger(), + "unable to load chainhook associated with key {}: {}", + key, + e.to_string() + ); + continue; + } + }; + chainhook_config.register_hook(chainhook); + } + } + + let event_observer_config = EventObserverConfig { + normalization_enabled: true, + grpc_server_enabled: false, + hooks_enabled: true, + bitcoin_rpc_proxy_enabled: true, + event_handlers: vec![], + chainhook_config: Some(chainhook_config), + ingestion_port: DEFAULT_INGESTION_PORT, + control_port: DEFAULT_CONTROL_PORT, + bitcoin_node_username: config.network.bitcoin_node_rpc_username.clone(), + bitcoin_node_password: config.network.bitcoin_node_rpc_password.clone(), + bitcoin_node_rpc_url: config.network.bitcoin_node_rpc_url.clone(), + stacks_node_rpc_url: config.network.stacks_node_rpc_url.clone(), + operators: HashSet::new(), + display_logs: false, + }; + info!( + ctx.expect_logger(), + "Listening for new blockchain events on port {}", DEFAULT_INGESTION_PORT + ); + info!( + ctx.expect_logger(), + "Listening for chainhook predicate registrations on port {}", DEFAULT_CONTROL_PORT + ); + let context_cloned = ctx.clone(); + let _ = std::thread::spawn(move || { + let future = start_event_observer( + event_observer_config, + observer_command_tx, + observer_command_rx, + Some(observer_event_tx), + context_cloned, + ); + let _ = hiro_system_kit::nestable_block_on(future); + }); + + loop { + let event = match observer_event_rx.recv() { + Ok(cmd) => cmd, + Err(e) => { + error!( + ctx.expect_logger(), + "Error: broken channel {}", + e.to_string() + ); + break; + } + }; + let redis_config = config.expected_redis_config(); + let client = redis::Client::open(redis_config.uri.clone()).unwrap(); + let mut redis_con = match client.get_connection() { + Ok(con) => con, + Err(message) => { + error!(ctx.expect_logger(), "Redis: {}", message.to_string()); + panic!(); + } + }; + match event { + ObserverEvent::HookRegistered(chainhook) => { + // If start block specified, use it. + // I no start block specified, depending on the nature the hook, we'd like to retrieve: + // - contract-id + + let chainhook_key = chainhook.key(); + let mut history: Vec = vec![]; + let res: Result<(), redis::RedisError> = redis_con.hset_multiple( + &chainhook_key, + &[ + ("specification", json!(chainhook).to_string()), + ("history", json!(history).to_string()), + ("scan_progress", json!(0).to_string()), + ], + ); + if let Err(e) = res { + error!( + ctx.expect_logger(), + "unable to store chainhook {chainhook_key}: {}", + e.to_string() + ); + } + match chainhook { + ChainhookSpecification::Stacks(stacks_hook) => { + // Retrieve highest block height stored + let tip_height: u64 = redis_con.get(&format!("stx:tip")).unwrap_or(1); + + let start_block = stacks_hook.start_block.unwrap_or(1); // TODO(lgalabru): handle STX hooks and genesis block :s + let end_block = stacks_hook.end_block.unwrap_or(tip_height); // TODO(lgalabru): handle STX hooks and genesis block :s + + info!( + ctx.expect_logger(), + "Processing Stacks chainhook {}, will scan blocks [{}; {}]", + stacks_hook.uuid, + start_block, + end_block + ); + let mut total_hits = 0; + for cursor in start_block..=end_block { + debug!( + ctx.expect_logger(), + "Evaluating predicate #{} on block #{}", stacks_hook.uuid, cursor + ); + let ( + block_identifier, + parent_block_identifier, + timestamp, + transactions, + metadata, + ) = { + let payload: Vec = redis_con + .hget( + &format!("stx:{}", cursor), + &[ + "block_identifier", + "parent_block_identifier", + "timestamp", + "transactions", + "metadata", + ], + ) + .expect("unable to retrieve tip height"); + if payload.len() != 5 { + warn!(ctx.expect_logger(), "Chain still being processed, please retry in a few minutes"); + continue; + } + ( + serde_json::from_str::(&payload[0]).unwrap(), + serde_json::from_str::(&payload[1]).unwrap(), + serde_json::from_str::(&payload[2]).unwrap(), + serde_json::from_str::>(&payload[3]) + .unwrap(), + serde_json::from_str::(&payload[4]) + .unwrap(), + ) + }; + let mut hits = vec![]; + for tx in transactions.iter() { + if evaluate_stacks_transaction_predicate_on_transaction( + &tx, + &stacks_hook, + &ctx, + ) { + debug!( + ctx.expect_logger(), + "Action #{} triggered by transaction {} (block #{})", + stacks_hook.uuid, + tx.transaction_identifier.hash, + cursor + ); + hits.push(tx); + total_hits += 1; + } + } + + if hits.len() > 0 { + let block = StacksBlockData { + block_identifier, + parent_block_identifier, + timestamp, + transactions: vec![], + metadata, + }; + let trigger = StacksTriggerChainhook { + chainhook: &stacks_hook, + apply: vec![(hits, &block)], + rollback: vec![], + }; + + let proofs = HashMap::new(); + if let Some(result) = + handle_stacks_hook_action(trigger, &proofs, &ctx) + { + if let StacksChainhookOccurrence::Http(request) = result { + hiro_system_kit::nestable_block_on(request.send()).unwrap(); + } + } + } + } + info!(ctx.expect_logger(), "Stacks chainhook {} scan completed: action triggered by {} transactions", stacks_hook.uuid, total_hits); + } + ChainhookSpecification::Bitcoin(_bitcoin_hook) => { + warn!( + ctx.expect_logger(), + "Bitcoin chainhook evaluation unavailable for historical data" + ); + } + } + } + ObserverEvent::HookDeregistered(chainhook) => { + let chainhook_key = chainhook.key(); + let _: Result<(), redis::RedisError> = redis_con.del(chainhook_key); + } + ObserverEvent::BitcoinChainEvent(_chain_update) => { + debug!(ctx.expect_logger(), "Bitcoin update not stored"); + } + ObserverEvent::StacksChainEvent(chain_event) => { + match &chain_event { + StacksChainEvent::ChainUpdatedWithBlocks(data) => { + update_storage_with_confirmed_stacks_blocks( + &mut redis_con, + &data.confirmed_blocks, + &ctx, + ); + } + StacksChainEvent::ChainUpdatedWithReorg(data) => { + update_storage_with_confirmed_stacks_blocks( + &mut redis_con, + &data.confirmed_blocks, + &ctx, + ); + } + StacksChainEvent::ChainUpdatedWithMicroblocks(_) + | StacksChainEvent::ChainUpdatedWithMicroblocksReorg(_) => {} + }; + } + ObserverEvent::Terminate => { + break; + } + _ => {} + } + } +} + +fn update_storage_with_confirmed_stacks_blocks( + redis_con: &mut Connection, + blocks: &Vec, + ctx: &Context, +) { + let current_tip_height: u64 = redis_con.get(&format!("stx:tip")).unwrap_or(0); + + let mut new_tip = None; + + for block in blocks.iter() { + let res: Result<(), redis::RedisError> = redis_con.hset_multiple( + &format!("stx:{}", block.block_identifier.index), + &[ + ( + "block_identifier", + json!(block.block_identifier).to_string(), + ), + ( + "parent_block_identifier", + json!(block.parent_block_identifier).to_string(), + ), + ("transactions", json!(block.transactions).to_string()), + ("metadata", json!(block.metadata).to_string()), + ], + ); + if let Err(error) = res { + crit!( + ctx.expect_logger(), + "unable to archive block {}: {}", + block.block_identifier, + error.to_string() + ); + } + if block.block_identifier.index >= current_tip_height { + new_tip = Some(block); + } + } + + if let Some(block) = new_tip { + info!( + ctx.expect_logger(), + "Archiving confirmed Stacks chain block {}", block.block_identifier + ); + let _: Result<(), redis::RedisError> = + redis_con.set(&format!("stx:tip"), block.block_identifier.index); + } +} diff --git a/components/chainhook-cli/src/config/file.rs b/components/chainhook-cli/src/config/file.rs new file mode 100644 index 0000000..b9674e2 --- /dev/null +++ b/components/chainhook-cli/src/config/file.rs @@ -0,0 +1,38 @@ +#[derive(Deserialize, Debug, Clone)] +pub struct ConfigFile { + pub storage: StorageConfigFile, + pub event_source: Option>, + pub chainhooks: ChainhooksConfigFile, + pub network: NetworkConfigFile, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct StorageConfigFile { + pub driver: String, + pub redis_uri: String, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct EventSourceConfigFile { + pub source_type: Option, + pub stacks_node_url: Option, + pub chainhook_node_url: Option, + pub polling_delay: Option, + pub tsv_file_path: Option, + pub tsv_file_url: Option, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct ChainhooksConfigFile { + pub max_stacks_registrations: Option, + pub max_bitcoin_registrations: Option, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct NetworkConfigFile { + pub mode: String, + pub bitcoin_node_rpc_url: String, + pub bitcoin_node_rpc_username: String, + pub bitcoin_node_rpc_password: String, + pub stacks_node_rpc_url: String, +} diff --git a/components/chainhook-cli/src/config/mod.rs b/components/chainhook-cli/src/config/mod.rs new file mode 100644 index 0000000..3c3a4ed --- /dev/null +++ b/components/chainhook-cli/src/config/mod.rs @@ -0,0 +1,302 @@ +pub mod file; + +pub use chainhook_event_observer::indexer::IndexerConfig; +use chainhook_types::{BitcoinNetwork, StacksNetwork}; +pub use file::ConfigFile; +use std::fs::File; +use std::io::{BufReader, Read}; +use std::path::PathBuf; + +const DEFAULT_MAINNET_TSV_ARCHIVE: &str = "https://storage.googleapis.com/hirosystems-archive/mainnet/api/mainnet-blockchain-api-latest.tar.gz"; +const DEFAULT_TESTNET_TSV_ARCHIVE: &str = "https://storage.googleapis.com/hirosystems-archive/testnet/api/testnet-blockchain-api-latest.tar.gz"; + +#[derive(Clone, Debug)] +pub struct Config { + pub storage: StorageConfig, + pub event_sources: Vec, + pub chainhooks: ChainhooksConfig, + pub network: IndexerConfig, +} + +#[derive(Clone, Debug)] +pub struct StorageConfig { + pub driver: StorageDriver, + pub cache_path: String, +} + +#[derive(Clone, Debug)] +pub enum StorageDriver { + Redis(RedisConfig), +} + +#[derive(Clone, Debug)] +pub struct RedisConfig { + pub uri: String, +} + +#[derive(Clone, Debug)] +pub enum EventSourceConfig { + StacksNode(StacksNodeConfig), + TsvPath(TsvPathConfig), + TsvUrl(TsvUrlConfig), +} + +#[derive(Clone, Debug)] +pub struct TsvPathConfig { + pub file_path: PathBuf, +} + +#[derive(Clone, Debug)] +pub struct TsvUrlConfig { + pub file_url: String, +} + +#[derive(Clone, Debug)] +pub struct StacksNodeConfig { + pub host: String, +} + +#[derive(Clone, Debug)] +pub struct ChainhooksConfig { + pub max_stacks_registrations: u16, + pub max_bitcoin_registrations: u16, +} + +impl Config { + pub fn from_file_path(file_path: &str) -> Result { + let file = File::open(file_path) + .map_err(|e| format!("unable to read file {}\n{:?}", file_path, e))?; + let mut file_reader = BufReader::new(file); + let mut file_buffer = vec![]; + file_reader + .read_to_end(&mut file_buffer) + .map_err(|e| format!("unable to read file {}\n{:?}", file_path, e))?; + + let config_file: ConfigFile = match toml::from_slice(&file_buffer) { + Ok(s) => s, + Err(e) => { + return Err(format!("Config file malformatted {}", e.to_string())); + } + }; + Config::from_config_file(config_file) + } + + pub fn from_config_file(config_file: ConfigFile) -> Result { + let (stacks_network, bitcoin_network) = match config_file.network.mode.as_str() { + "devnet" => (StacksNetwork::Devnet, BitcoinNetwork::Regtest), + "testnet" => (StacksNetwork::Testnet, BitcoinNetwork::Testnet), + "mainnet" => (StacksNetwork::Mainnet, BitcoinNetwork::Mainnet), + _ => return Err("network.mode not supported".to_string()), + }; + + let config = Config { + storage: StorageConfig { + driver: StorageDriver::Redis(RedisConfig { + uri: config_file.storage.redis_uri.to_string(), + }), + cache_path: "cache".into(), + }, + event_sources: vec![EventSourceConfig::StacksNode(StacksNodeConfig { + host: config_file.network.stacks_node_rpc_url.to_string(), + })], + chainhooks: ChainhooksConfig { + max_stacks_registrations: config_file + .chainhooks + .max_stacks_registrations + .unwrap_or(100), + max_bitcoin_registrations: config_file + .chainhooks + .max_bitcoin_registrations + .unwrap_or(100), + }, + network: IndexerConfig { + stacks_node_rpc_url: config_file.network.stacks_node_rpc_url.to_string(), + bitcoin_node_rpc_url: config_file.network.bitcoin_node_rpc_url.to_string(), + bitcoin_node_rpc_username: config_file + .network + .bitcoin_node_rpc_username + .to_string(), + bitcoin_node_rpc_password: config_file + .network + .bitcoin_node_rpc_password + .to_string(), + stacks_network, + bitcoin_network, + }, + }; + Ok(config) + } + + pub fn is_initial_ingestion_required(&self) -> bool { + for source in self.event_sources.iter() { + match source { + EventSourceConfig::TsvUrl(_) | EventSourceConfig::TsvPath(_) => return true, + EventSourceConfig::StacksNode(_) => {} + } + } + return false; + } + + pub fn add_local_tsv_source(&mut self, file_path: &PathBuf) { + self.event_sources + .push(EventSourceConfig::TsvPath(TsvPathConfig { + file_path: file_path.clone(), + })); + } + + pub fn expected_redis_config(&self) -> &RedisConfig { + match self.storage.driver { + StorageDriver::Redis(ref conf) => conf, + } + } + + pub fn expected_local_tsv_file(&self) -> &PathBuf { + for source in self.event_sources.iter() { + if let EventSourceConfig::TsvPath(config) = source { + return &config.file_path; + } + } + panic!("expected local-tsv source") + } + + pub fn expected_cache_path(&self) -> PathBuf { + let mut destination_path = std::env::current_dir().expect("unable to get current dir"); + destination_path.push(&self.storage.cache_path); + destination_path + } + + pub fn expected_stacks_node_event_source(&self) -> &String { + for source in self.event_sources.iter() { + if let EventSourceConfig::StacksNode(config) = source { + return &config.host; + } + } + panic!("expected remote-tsv source") + } + + pub fn expected_remote_tsv_url(&self) -> &String { + for source in self.event_sources.iter() { + if let EventSourceConfig::TsvUrl(config) = source { + return &config.file_url; + } + } + panic!("expected remote-tsv source") + } + + pub fn rely_on_remote_tsv(&self) -> bool { + for source in self.event_sources.iter() { + if let EventSourceConfig::TsvUrl(_config) = source { + return true; + } + } + false + } + + pub fn should_download_remote_tsv(&self) -> bool { + let mut rely_on_remote_tsv = false; + let mut remote_tsv_present_locally = false; + for source in self.event_sources.iter() { + if let EventSourceConfig::TsvUrl(_config) = source { + rely_on_remote_tsv = true; + } + if let EventSourceConfig::TsvPath(_config) = source { + remote_tsv_present_locally = true; + } + } + rely_on_remote_tsv == true && remote_tsv_present_locally == false + } + + pub fn default( + devnet: bool, + testnet: bool, + mainnet: bool, + config_path: &Option, + ) -> Result { + let config = match (devnet, testnet, mainnet, config_path) { + (true, false, false, _) => Config::devnet_default(), + (false, true, false, _) => Config::testnet_default(), + (false, false, true, _) => Config::mainnet_default(), + (false, false, false, Some(config_path)) => Config::from_file_path(&config_path)?, + _ => Err("Invalid combination of arguments".to_string())?, + }; + Ok(config) + } + + pub fn devnet_default() -> Config { + Config { + storage: StorageConfig { + driver: StorageDriver::Redis(RedisConfig { + uri: "redis://localhost:6379/".into(), + }), + cache_path: "cache".into(), + }, + event_sources: vec![EventSourceConfig::StacksNode(StacksNodeConfig { + host: "http://0.0.0.0:20443".into(), + })], + chainhooks: ChainhooksConfig { + max_stacks_registrations: 50, + max_bitcoin_registrations: 50, + }, + network: IndexerConfig { + stacks_node_rpc_url: "http://0.0.0.0:20443".into(), + bitcoin_node_rpc_url: "http://0.0.0.0:18443".into(), + bitcoin_node_rpc_username: "devnet".into(), + bitcoin_node_rpc_password: "devnet".into(), + stacks_network: StacksNetwork::Devnet, + bitcoin_network: BitcoinNetwork::Regtest, + }, + } + } + + pub fn testnet_default() -> Config { + Config { + storage: StorageConfig { + driver: StorageDriver::Redis(RedisConfig { + uri: "redis://localhost:6379/".into(), + }), + cache_path: "cache".into(), + }, + event_sources: vec![EventSourceConfig::TsvUrl(TsvUrlConfig { + file_url: DEFAULT_TESTNET_TSV_ARCHIVE.into(), + })], + chainhooks: ChainhooksConfig { + max_stacks_registrations: 10, + max_bitcoin_registrations: 10, + }, + network: IndexerConfig { + stacks_node_rpc_url: "http://0.0.0.0:20443".into(), + bitcoin_node_rpc_url: "http://0.0.0.0:18332".into(), + bitcoin_node_rpc_username: "devnet".into(), + bitcoin_node_rpc_password: "devnet".into(), + stacks_network: StacksNetwork::Testnet, + bitcoin_network: BitcoinNetwork::Testnet, + }, + } + } + + pub fn mainnet_default() -> Config { + Config { + storage: StorageConfig { + driver: StorageDriver::Redis(RedisConfig { + uri: "redis://localhost:6379/".into(), + }), + cache_path: "cache".into(), + }, + event_sources: vec![EventSourceConfig::TsvUrl(TsvUrlConfig { + file_url: DEFAULT_MAINNET_TSV_ARCHIVE.into(), + })], + chainhooks: ChainhooksConfig { + max_stacks_registrations: 10, + max_bitcoin_registrations: 10, + }, + network: IndexerConfig { + stacks_node_rpc_url: "http://0.0.0.0:20443".into(), + bitcoin_node_rpc_url: "http://0.0.0.0:8332".into(), + bitcoin_node_rpc_username: "devnet".into(), + bitcoin_node_rpc_password: "devnet".into(), + stacks_network: StacksNetwork::Mainnet, + bitcoin_network: BitcoinNetwork::Mainnet, + }, + } + } +} diff --git a/components/chainhook-cli/src/main.rs b/components/chainhook-cli/src/main.rs new file mode 100644 index 0000000..f97a1ec --- /dev/null +++ b/components/chainhook-cli/src/main.rs @@ -0,0 +1,19 @@ +#[macro_use] +extern crate serde_json; + +#[macro_use] +extern crate hiro_system_kit; + +#[macro_use] +extern crate serde_derive; + +extern crate serde; + +pub mod archive; +pub mod block; +mod cli; +pub mod config; + +fn main() { + cli::main(); +} diff --git a/components/chainhook-event-observer/Cargo.lock b/components/chainhook-event-observer/Cargo.lock new file mode 100644 index 0000000..aa2f819 --- /dev/null +++ b/components/chainhook-event-observer/Cargo.lock @@ -0,0 +1,3929 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aead" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c192eb8f11fc081b0fe4259ba5af04217d4e0faddd02417310a927911abd7c8" +dependencies = [ + "crypto-common", + "generic-array 0.14.5", +] + +[[package]] +name = "aes" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433cfd6710c9986c576a25ca913c39d66a6474107b406f34f91d4a8923395241" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82e1366e0c69c9f927b1fa5ce2c7bf9eafc8f9268c0b9800729e8b267612447c" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "ahash" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +dependencies = [ + "getrandom 0.2.6", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "ansi_term" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" +dependencies = [ + "winapi", +] + +[[package]] +name = "arc-swap" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" + +[[package]] +name = "arrayref" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" + +[[package]] +name = "arrayvec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" + +[[package]] +name = "async-stream" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad5c83079eae9969be7fadefe640a1c566901f05ff91ab221de4b6f68d9507e" +dependencies = [ + "async-stream-impl", + "futures-core", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10f203db73a71dfa2fb6dd22763990fa26f3d2625a6da2da900d23b87d26be27" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "async-trait" +version = "0.1.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed6aa3524a2dfcf9fe180c51eae2b58738348d819517ceadf95789c51fff7600" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "atomic" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b88d82667eca772c4aa12f0f1348b3ae643424c8876448f3f7bd5787032e234c" +dependencies = [ + "autocfg", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "base-x" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc19a4937b4fbd3fe3379793130e42060d10627a360f2127802b10b87e7baf74" + +[[package]] +name = "base58" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6107fe1be6682a68940da878d9e9f5e90ca5745b3dec9fd1bb393c8777d4f581" + +[[package]] +name = "base64" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff" + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + +[[package]] +name = "base64" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea22880d78093b0cbe17c89f64a7d457941e65759157ec6cb31a31d652b05e5" + +[[package]] +name = "base64-compat" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a8d4d2746f89841e49230dd26917df1876050f95abafafbe34f47cb534b88d7" +dependencies = [ + "byteorder", +] + +[[package]] +name = "base64ct" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b645a089122eccb6111b4f81cbc1a49f5900ac4666bb93ac027feaecf15607bf" + +[[package]] +name = "bech32" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d86b93f97252c47b41663388e6d155714a9d0c398b99f1005cbc5f978b29f445" + +[[package]] +name = "binascii" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" + +[[package]] +name = "bitcoin" +version = "0.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0694ea59225b0c5f3cb405ff3f670e4828358ed26aec49dc352f730f0cb1a8a3" +dependencies = [ + "bech32", + "bitcoin_hashes", + "secp256k1 0.24.2", + "serde", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90064b8dee6815a6470d60bad07bbbaee885c0e12d04177138fa3291a01b7bc4" +dependencies = [ + "serde", +] + +[[package]] +name = "bitcoincore-rpc" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0261b2bb7617e0c91b452a837bbd1291fd34ad6990cb8e3ffc28239cc045b5ca" +dependencies = [ + "bitcoincore-rpc-json", + "jsonrpc", + "log", + "serde", + "serde_json", +] + +[[package]] +name = "bitcoincore-rpc-json" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c231bea28e314879c5aef240f6052e8a72a369e3c9f9b20d9bfbb33ad18029b2" +dependencies = [ + "bitcoin", + "serde", + "serde_json", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "blake2b_simd" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" +dependencies = [ + "arrayref", + "arrayvec", + "constant_time_eq", +] + +[[package]] +name = "block-buffer" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" +dependencies = [ + "block-padding 0.1.5", + "byte-tools", + "byteorder", + "generic-array 0.12.4", +] + +[[package]] +name = "block-buffer" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" +dependencies = [ + "block-padding 0.2.1", + "generic-array 0.14.5", +] + +[[package]] +name = "block-buffer" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e" +dependencies = [ + "generic-array 0.14.5", +] + +[[package]] +name = "block-padding" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" +dependencies = [ + "byte-tools", +] + +[[package]] +name = "block-padding" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" + +[[package]] +name = "bstr" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" +dependencies = [ + "lazy_static", + "memchr", + "regex-automata", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a45a46ab1f2412e53d3a0ade76ffad2025804294569aae387231a0cd6e0899" + +[[package]] +name = "byte-tools" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" + +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chainhook-event-observer" +version = "1.0.0" +dependencies = [ + "base58", + "base64 0.13.0", + "bitcoincore-rpc", + "bitcoincore-rpc-json", + "chainhook-types", + "clap", + "clap_generate", + "clarinet-utils", + "clarity-repl", + "crossbeam-channel", + "ctrlc", + "hiro-system-kit", + "reqwest", + "rocket", + "rocket_okapi", + "schemars", + "serde", + "serde_derive", + "serde_json", + "stacks-rpc-client", + "tokio", + "toml", +] + +[[package]] +name = "chainhook-types" +version = "1.0.0" +dependencies = [ + "schemars", + "serde", + "serde_derive", + "serde_json", + "strum", +] + +[[package]] +name = "chrono" +version = "0.4.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-integer", + "num-traits", + "time 0.1.45", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "cipher" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1873270f8f7942c191139cb8a40fd228da6c3fd2fc376d7e92d47aa14aeb59e" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "3.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85a35a599b11c089a7f49105658d089b8f2cf0882993c17daf6de15285c2c35d" +dependencies = [ + "atty", + "bitflags", + "clap_derive", + "clap_lex", + "indexmap", + "lazy_static", + "strsim", + "termcolor", + "textwrap", +] + +[[package]] +name = "clap_complete" +version = "3.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7ca9141e27e6ebc52e3c378b0c07f3cea52db46ed1cc5861735fb697b56356" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "3.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1" +dependencies = [ + "heck 0.4.0", + "proc-macro-error", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_generate" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1b28c4a802ac3628604fd267cac62aaea74dc61af3410db6b1c44c03b42599" +dependencies = [ + "clap", + "clap_complete", +] + +[[package]] +name = "clap_lex" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "clarinet-utils" +version = "1.0.0" +dependencies = [ + "hmac 0.12.1", + "pbkdf2", + "serde", + "sha2 0.10.6", +] + +[[package]] +name = "clarity" +version = "0.0.1" +source = "git+https://github.com/stacks-network/stacks-blockchain.git?rev=601ac7a0b4ed3de027382a33560d079aaa337b4d#601ac7a0b4ed3de027382a33560d079aaa337b4d" +dependencies = [ + "integer-sqrt", + "lazy_static", + "rand 0.7.3", + "rand_chacha 0.2.2", + "regex", + "rstest", + "rstest_reuse", + "rusqlite", + "serde", + "serde_derive", + "serde_json", + "serde_stacker", + "sha2-asm", + "stacks-common", + "time 0.2.27", +] + +[[package]] +name = "clarity-repl" +version = "1.3.1" +dependencies = [ + "ansi_term", + "atty", + "bytes", + "clarity", + "debug_types", + "futures", + "getrandom 0.2.6", + "hiro-system-kit", + "httparse", + "integer-sqrt", + "lazy_static", + "libsecp256k1", + "log", + "memchr", + "pico-args", + "prettytable-rs", + "rand 0.7.3", + "rand_pcg", + "rand_seeder", + "regex", + "reqwest", + "ripemd160", + "rustyline", + "serde", + "serde_derive", + "serde_json", + "sha2 0.10.6", + "sha3 0.9.1", + "tokio", + "tokio-util 0.7.1", +] + +[[package]] +name = "clear_on_drop" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38508a63f4979f0048febc9966fadbd48e5dab31fd0ec6a3f151bbf4a74f7423" +dependencies = [ + "cc", +] + +[[package]] +name = "clipboard-win" +version = "4.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3e1238132dc01f081e1cbb9dace14e5ef4c3a51ee244bd982275fb514605db" +dependencies = [ + "error-code", + "str-buf", + "winapi", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + +[[package]] +name = "const_fn" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbdcdcb6d86f71c5e97409ad45898af11cbc995b4ee8112d59095a28d376c935" + +[[package]] +name = "constant_time_eq" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" + +[[package]] +name = "cookie" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" +dependencies = [ + "aes-gcm", + "base64 0.20.0", + "hkdf", + "hmac 0.12.1", + "percent-encoding", + "rand 0.8.5", + "sha2 0.10.6", + "subtle", + "time 0.3.17", + "version_check", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" + +[[package]] +name = "cpufeatures" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" +dependencies = [ + "libc", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" +dependencies = [ + "cfg-if", + "lazy_static", +] + +[[package]] +name = "crunchy" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array 0.14.5", + "rand_core 0.6.3", + "typenum", +] + +[[package]] +name = "crypto-mac" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b584a330336237c1eecd3e94266efb216c56ed91225d634cb2991c5f3fd1aeab" +dependencies = [ + "generic-array 0.14.5", + "subtle", +] + +[[package]] +name = "csv" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" +dependencies = [ + "bstr", + "csv-core", + "itoa 0.4.8", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" +dependencies = [ + "memchr", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctrlc" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b37feaa84e6861e00a1f5e5aa8da3ee56d605c9992d33e082786754828e20865" +dependencies = [ + "nix 0.24.1", + "winapi", +] + +[[package]] +name = "curve25519-dalek" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26778518a7f6cffa1d25a44b602b62b979bd88adb9e99ffec546998cf3404839" +dependencies = [ + "byteorder", + "digest 0.8.1", + "rand_core 0.5.1", + "serde", + "subtle", + "zeroize", +] + +[[package]] +name = "cxx" +version = "1.0.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e599641dff337570f6aa9c304ecca92341d30bf72e1c50287869ed6a36615a6" +dependencies = [ + "cc", + "cxxbridge-flags", + "cxxbridge-macro", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60e2434bc22249c056e12d2e87db46380730da0f2648471edea3e8e11834a892" +dependencies = [ + "cc", + "codespan-reporting", + "once_cell", + "proc-macro2", + "quote", + "scratch", + "syn", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3894ad0c6d517cb5a4ce8ec20b37cd0ea31b480fe582a104c5db67ae21270853" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34fa7e395dc1c001083c7eed28c8f0f0b5a225610f3b6284675f444af6fab86b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "darling" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "debug_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2613f33760bd27a70ee84f5a8c0bd97e874fa6f89e205356ef8325786dd22cef" +dependencies = [ + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "devise" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c7580b072f1c8476148f16e0a0d5dedddab787da98d86c5082c5e9ed8ab595" +dependencies = [ + "devise_codegen", + "devise_core", +] + +[[package]] +name = "devise_codegen" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "123c73e7a6e51b05c75fe1a1b2f4e241399ea5740ed810b0e3e6cacd9db5e7b2" +dependencies = [ + "devise_core", + "quote", +] + +[[package]] +name = "devise_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841ef46f4787d9097405cac4e70fb8644fc037b526e8c14054247c0263c400d0" +dependencies = [ + "bitflags", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn", +] + +[[package]] +name = "digest" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" +dependencies = [ + "generic-array 0.12.4", +] + +[[package]] +name = "digest" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" +dependencies = [ + "generic-array 0.14.5", +] + +[[package]] +name = "digest" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" +dependencies = [ + "block-buffer 0.10.3", + "crypto-common", + "subtle", +] + +[[package]] +name = "dirs" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fd78930633bd1c6e35c4b42b1df7b0cbc6bc191146e512bb3bedf243fcc3901" +dependencies = [ + "libc", + "redox_users 0.3.5", + "winapi", +] + +[[package]] +name = "dirs-next" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" +dependencies = [ + "cfg-if", + "dirs-sys-next", +] + +[[package]] +name = "dirs-sys-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" +dependencies = [ + "libc", + "redox_users 0.4.3", + "winapi", +] + +[[package]] +name = "discard" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" + +[[package]] +name = "dyn-clone" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9b0705efd4599c15a38151f4721f7bc388306f61084d3bfd50bd07fbca5cb60" + +[[package]] +name = "ed25519-dalek" +version = "1.0.0-pre.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "978710b352437433c97b2bff193f2fb1dfd58a093f863dd95e225a19baa599a2" +dependencies = [ + "clear_on_drop", + "curve25519-dalek", + "rand 0.7.3", + "serde", + "sha2 0.8.2", +] + +[[package]] +name = "either" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" + +[[package]] +name = "encode_unicode" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" + +[[package]] +name = "encoding_rs" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "endian-type" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34f04666d835ff5d62e058c3995147c06f42fe86ff053337632bca83e42702d" + +[[package]] +name = "errno" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" +dependencies = [ + "errno-dragonfly", + "libc", + "winapi", +] + +[[package]] +name = "errno-dragonfly" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "error-code" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f18991e7bf11e7ffee451b5318b5c1a73c52d0d0ada6e5a3017c8c1ced6a21" +dependencies = [ + "libc", + "str-buf", +] + +[[package]] +name = "fake-simd" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" +dependencies = [ + "instant", +] + +[[package]] +name = "fd-lock" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46e245f4c8ec30c6415c56cb132c07e69e74f1942f6b4a4061da748b49f486ca" +dependencies = [ + "cfg-if", + "rustix", + "windows-sys 0.30.0", +] + +[[package]] +name = "figment" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790b4292c72618abbab50f787a477014fe15634f96291de45672ce46afe122df" +dependencies = [ + "atomic", + "pear", + "serde", + "toml", + "uncased", + "version_check", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" +dependencies = [ + "matches", + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f73fe65f54d1e12b726f517d3e2135ca3125a437b6d998caf1962961f7172d9e" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" + +[[package]] +name = "futures-executor" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" + +[[package]] +name = "futures-macro" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" + +[[package]] +name = "futures-task" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a" + +[[package]] +name = "futures-util" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generator" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1d9279ca822891c1a4dae06d185612cf8fc6acfe5dff37781b41297811b12ee" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "winapi", +] + +[[package]] +name = "generic-array" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" +dependencies = [ + "typenum", +] + +[[package]] +name = "generic-array" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d930750de5717d2dd0b8c0d42c076c0e884c81a73e6cab859bbd2339c71e3e40" +dependencies = [ + "opaque-debug 0.3.0", + "polyval", +] + +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + +[[package]] +name = "h2" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37a82c6d637fc9515a4694bbf1cb2457b79d81ce52b3108bdeea58b07dd34a57" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util 0.7.1", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7249a3129cbc1ffccd74857f81464a323a152173cdb134e0fd81bc803b29facf" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "heck" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "heck" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "hiro-system-kit" +version = "0.1.0" +dependencies = [ + "ansi_term", + "atty", + "futures", + "lazy_static", + "slog", + "slog-async", + "slog-atomic", + "slog-json", + "slog-scope", + "slog-term", + "tokio", +] + +[[package]] +name = "hkdf" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" +dependencies = [ + "hmac 0.12.1", +] + +[[package]] +name = "hmac" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "126888268dcc288495a26bf004b38c5fdbb31682f992c84ceb046a1f0fe38840" +dependencies = [ + "crypto-mac", + "digest 0.9.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.6", +] + +[[package]] +name = "hmac-drbg" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17ea0a1394df5b6574da6e0c1ade9e78868c9fb0a4e5ef4428e32da4676b85b1" +dependencies = [ + "digest 0.9.0", + "generic-array 0.14.5", + "hmac 0.8.1", +] + +[[package]] +name = "http" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff8670570af52249509a86f5e3e18a08c60b177071826898fde8997cf5f6bfbb" +dependencies = [ + "bytes", + "fnv", + "itoa 1.0.1", +] + +[[package]] +name = "http-body" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ff4f84919677303da5f147645dbea6b1881f368d03ac84e1dc09031ebd7b2c6" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "496ce29bb5a52785b44e0f7ca2847ae0bb839c9bd28f69acac9b99d461c0c04c" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "hyper" +version = "0.14.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b26ae0a80afebe130861d90abf98e3814a4f28a4c6ffeb5ab8ebb2be311e0ef2" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa 1.0.1", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87c48c02e0dc5e3b849a2041db3029fd066650f8f717c07bf8ed78ccb895cac" +dependencies = [ + "http", + "hyper", + "rustls", + "tokio", + "tokio-rustls", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +dependencies = [ + "cxx", + "cxx-build", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" +dependencies = [ + "matches", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "indexmap" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" +dependencies = [ + "autocfg", + "hashbrown", + "serde", +] + +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array 0.14.5", +] + +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "integer-sqrt" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "276ec31bcb4a9ee45f58bec6f9ec700ae4cf4f4f8f2fa7e06cb406bd5ffdd770" +dependencies = [ + "num-traits", +] + +[[package]] +name = "io-lifetimes" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9448015e586b611e5d322f6703812bbca2f1e709d5773ecd38ddb4e3bb649504" + +[[package]] +name = "ipnet" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879d54834c8c76457ef4293a689b2a8c59b076067ad77b15efafbb05f92a592b" + +[[package]] +name = "itoa" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" + +[[package]] +name = "itoa" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" + +[[package]] +name = "js-sys" +version = "0.3.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "jsonrpc" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8423b78fc94d12ef1a4a9d13c348c9a78766dda0cc18817adf0faf77e670c8" +dependencies = [ + "base64-compat", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "keccak" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c21572b4949434e4fc1e1978b99c5f77064153c59d998bf13ecd96fb5ecba7" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.139" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" + +[[package]] +name = "libsecp256k1" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd1137239ab33b41aa9637a88a28249e5e70c40a42ccc92db7f12cc356c1fcd7" +dependencies = [ + "arrayref", + "base64 0.12.3", + "digest 0.9.0", + "hmac-drbg", + "libsecp256k1-core", + "libsecp256k1-gen-ecmult", + "libsecp256k1-gen-genmult", + "rand 0.7.3", + "serde", + "sha2 0.9.9", + "typenum", +] + +[[package]] +name = "libsecp256k1-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0f6ab710cec28cef759c5f18671a27dae2a5f952cdaaee1d8e2908cb2478a80" +dependencies = [ + "crunchy", + "digest 0.9.0", + "subtle", +] + +[[package]] +name = "libsecp256k1-gen-ecmult" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccab96b584d38fac86a83f07e659f0deafd0253dc096dab5a36d53efe653c5c3" +dependencies = [ + "libsecp256k1-core", +] + +[[package]] +name = "libsecp256k1-gen-genmult" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67abfe149395e3aa1c48a2beb32b068e2334402df8181f818d3aee2b304c4f5d" +dependencies = [ + "libsecp256k1-core", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898745e570c7d0453cc1fbc4a701eb6c662ed54e8fec8b7d14be137ebeeb9d14" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "link-cplusplus" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" +dependencies = [ + "cc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4d2456c373231a208ad294c33dc5bff30051eafd954cd4caae83a712b12854d" + +[[package]] +name = "lock_api" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "loom" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc5c7d328e32cc4954e8e01193d7f0ef5ab257b5090b70a964e099a36034309" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matches" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" + +[[package]] +name = "mio" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de" +dependencies = [ + "libc", + "log", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys 0.42.0", +] + +[[package]] +name = "multer" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f8f35e687561d5c1667590911e6698a8cb714a134a7505718a182e7bc9d3836" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "log", + "memchr", + "mime", + "spin 0.9.3", + "tokio", + "tokio-util 0.6.9", + "version_check", +] + +[[package]] +name = "nibble_vec" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a5d83df9f36fe23f0c3648c6bbb8b0298bb5f1939c8f2704431371f4b84d43" +dependencies = [ + "smallvec", +] + +[[package]] +name = "nix" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6" +dependencies = [ + "bitflags", + "cc", + "cfg-if", + "libc", + "memoffset", +] + +[[package]] +name = "nix" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +dependencies = [ + "libc", +] + +[[package]] +name = "okapi" +version = "0.7.0-rc.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce66b6366e049880a35c378123fddb630b1a1a3c37fa1ca70caaf4a09f6e2893" +dependencies = [ + "log", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "once_cell" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" + +[[package]] +name = "opaque-debug" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" + +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + +[[package]] +name = "os_str_bytes" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64" + +[[package]] +name = "parking_lot" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.2.13", + "smallvec", + "windows-sys 0.36.1", +] + +[[package]] +name = "password-hash" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" +dependencies = [ + "base64ct", + "rand_core 0.6.3", + "subtle", +] + +[[package]] +name = "pbkdf2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +dependencies = [ + "digest 0.10.6", + "hmac 0.12.1", + "password-hash", + "sha2 0.10.6", +] + +[[package]] +name = "pear" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15e44241c5e4c868e3eaa78b7c1848cadd6344ed4f54d029832d32b415a58702" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82a5ca643c2303ecb740d506539deba189e16f2754040a42901cd8105d0282d0" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn", +] + +[[package]] +name = "percent-encoding" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" + +[[package]] +name = "pest" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f6e86fb9e7026527a0d46bc308b841d73170ef8f443e1807f6ef88526a816d4" +dependencies = [ + "thiserror", + "ucd-trie", +] + +[[package]] +name = "pico-args" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8bcd96cb740d03149cbad5518db9fd87126a10ab519c011893b1754134c468" + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" + +[[package]] +name = "polyval" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef234e08c11dfcb2e56f79fd70f6f2eb7f025c0ce2333e82f4f0518ecad30c6" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug 0.3.0", + "universal-hash", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" + +[[package]] +name = "prettytable-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fd04b170004fa2daccf418a7f8253aaf033c27760b5f225889024cf66d7ac2e" +dependencies = [ + "atty", + "csv", + "encode_unicode", + "lazy_static", + "term 0.5.2", + "unicode-width", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" + +[[package]] +name = "proc-macro2" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bf29726d67464d49fa6224a1d07936a8c08bb3fba727c7493f6cf1616fdaada" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "version_check", + "yansi", +] + +[[package]] +name = "psm" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" +dependencies = [ + "cc", +] + +[[package]] +name = "quote" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "radix_trie" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c069c179fcdc6a2fe24d8d18305cf085fdbd4f922c041943e203685d6a1c58fd" +dependencies = [ + "endian-type", + "nibble_vec", +] + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.3", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.3", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +dependencies = [ + "getrandom 0.2.6", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_pcg" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e" +dependencies = [ + "rand_core 0.6.3", +] + +[[package]] +name = "rand_seeder" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf2890aaef0aa82719a50e808de264f9484b74b442e1a3a0e5ee38243ac40bdb" +dependencies = [ + "rand_core 0.6.3", +] + +[[package]] +name = "redox_syscall" +version = "0.1.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" + +[[package]] +name = "redox_syscall" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" +dependencies = [ + "getrandom 0.1.16", + "redox_syscall 0.1.57", + "rust-argon2", +] + +[[package]] +name = "redox_users" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +dependencies = [ + "getrandom 0.2.6", + "redox_syscall 0.2.13", + "thiserror", +] + +[[package]] +name = "ref-cast" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685d58625b6c2b83e4cc88a27c4bf65adb7b6b16dbdc413e515c9405b47432ab" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a043824e29c94169374ac5183ac0ed43f5724dc4556b19568007486bd840fa1f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "regex" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" + +[[package]] +name = "remove_dir_all" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" +dependencies = [ + "winapi", +] + +[[package]] +name = "reqwest" +version = "0.11.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1f7aa4f35e5e8b4160449f51afc758f0ce6454315a9fa7d0d113e958c41eb" +dependencies = [ + "base64 0.13.0", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "hyper", + "hyper-rustls", + "ipnet", + "js-sys", + "lazy_static", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pemfile", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-rustls", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", + "winreg", +] + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin 0.5.2", + "untrusted", + "web-sys", + "winapi", +] + +[[package]] +name = "ripemd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.6", +] + +[[package]] +name = "ripemd160" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eca4ecc81b7f313189bf73ce724400a07da2a6dac19588b03c8bd76a2dcc251" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + +[[package]] +name = "rocket" +version = "0.5.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98ead083fce4a405feb349cf09abdf64471c6077f14e0ce59364aa90d4b99317" +dependencies = [ + "async-stream", + "async-trait", + "atomic", + "atty", + "binascii", + "bytes", + "either", + "figment", + "futures", + "indexmap", + "log", + "memchr", + "multer", + "num_cpus", + "parking_lot", + "pin-project-lite", + "rand 0.8.5", + "ref-cast", + "rocket_codegen", + "rocket_http", + "serde", + "serde_json", + "state", + "tempfile", + "time 0.3.17", + "tokio", + "tokio-stream", + "tokio-util 0.7.1", + "ubyte", + "version_check", + "yansi", +] + +[[package]] +name = "rocket_codegen" +version = "0.5.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6aeb6bb9c61e9cd2c00d70ea267bf36f76a4cc615e5908b349c2f9d93999b47" +dependencies = [ + "devise", + "glob", + "indexmap", + "proc-macro2", + "quote", + "rocket_http", + "syn", + "unicode-xid", +] + +[[package]] +name = "rocket_http" +version = "0.5.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ded65d127954de3c12471630bf4b81a2792f065984461e65b91d0fdaafc17a2" +dependencies = [ + "cookie", + "either", + "futures", + "http", + "hyper", + "indexmap", + "log", + "memchr", + "pear", + "percent-encoding", + "pin-project-lite", + "ref-cast", + "serde", + "smallvec", + "stable-pattern", + "state", + "time 0.3.17", + "tokio", + "uncased", +] + +[[package]] +name = "rocket_okapi" +version = "0.8.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "489f4f5b120762f7974e65b919fc462d0660fd8b839026d8985b850fe5acccb0" +dependencies = [ + "either", + "log", + "okapi", + "rocket", + "rocket_okapi_codegen", + "schemars", + "serde", + "serde_json", +] + +[[package]] +name = "rocket_okapi_codegen" +version = "0.8.0-rc.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54f94d1ffe41472e08463d7a2674f1db04dc4df745285e8369b33d3cfd6b0308" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "rocket_http", + "syn", +] + +[[package]] +name = "rstest" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2288c66aeafe3b2ed227c981f364f9968fa952ef0b30e84ada4486e7ee24d00a" +dependencies = [ + "cfg-if", + "proc-macro2", + "quote", + "rustc_version 0.4.0", + "syn", +] + +[[package]] +name = "rstest_reuse" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32c6cfaae58c048728261723a72b80a0aa9f3768e9a7da3b302a24d262525219" +dependencies = [ + "quote", + "rustc_version 0.3.3", + "syn", +] + +[[package]] +name = "rusqlite" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85127183a999f7db96d1a976a309eebbfb6ea3b0b400ddd8340190129de6eb7a" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "memchr", + "serde_json", + "smallvec", +] + +[[package]] +name = "rust-argon2" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" +dependencies = [ + "base64 0.13.0", + "blake2b_simd", + "constant_time_eq", + "crossbeam-utils", +] + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver 0.9.0", +] + +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver 1.0.16", +] + +[[package]] +name = "rustix" +version = "0.34.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3e74b3f02f2b6eb33790923756784614f456de79d821d6b2670dc7d5fbea807" +dependencies = [ + "bitflags", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys", + "winapi", +] + +[[package]] +name = "rustls" +version = "0.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fbfeb8d0ddb84706bc597a5574ab8912817c52a397f819e5b614e2265206921" +dependencies = [ + "log", + "ring", + "sct", + "webpki", +] + +[[package]] +name = "rustls-pemfile" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ee86d63972a7c661d1536fefe8c3c8407321c3df668891286de28abcd087360" +dependencies = [ + "base64 0.13.0", +] + +[[package]] +name = "rustversion" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2cc38e8fa666e2de3c4aba7edeb5ffc5246c1c2ed0e3d17e560aeeba736b23f" + +[[package]] +name = "rustyline" +version = "9.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db7826789c0e25614b03e5a54a0717a86f9ff6e6e5247f92b369472869320039" +dependencies = [ + "bitflags", + "cfg-if", + "clipboard-win", + "dirs-next", + "fd-lock", + "libc", + "log", + "memchr", + "nix 0.23.1", + "radix_trie", + "scopeguard", + "smallvec", + "unicode-segmentation", + "unicode-width", + "utf8parse", + "winapi", +] + +[[package]] +name = "ryu" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" + +[[package]] +name = "schemars" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a5fb6c61f29e723026dc8e923d94c694313212abbecbbe5f55a7748eec5b307" +dependencies = [ + "dyn-clone", + "indexmap", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f188d036977451159430f3b8dc82ec76364a42b7e289c2b18a9a18f4470058e9" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "scoped-tls" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "scratch" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2" + +[[package]] +name = "sct" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "secp256k1" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c42e6f1735c5f00f51e43e28d6634141f2bcad10931b2609ddd74a86d751260" +dependencies = [ + "secp256k1-sys 0.4.2", + "serde", +] + +[[package]] +name = "secp256k1" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9512ffd81e3a3503ed401f79c33168b9148c75038956039166cd750eaa037c3" +dependencies = [ + "bitcoin_hashes", + "secp256k1-sys 0.6.1", + "serde", +] + +[[package]] +name = "secp256k1-sys" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957da2573cde917463ece3570eab4a0b3f19de6f1646cde62e6fd3868f566036" +dependencies = [ + "cc", +] + +[[package]] +name = "secp256k1-sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83080e2c2fc1006e625be82e5d1eb6a43b7fd9578b617fcc55814daf286bba4b" +dependencies = [ + "cc", +] + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser 0.7.0", +] + +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser 0.10.2", +] + +[[package]] +name = "semver" +version = "1.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a" + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + +[[package]] +name = "serde" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f972498cf015f7c0746cac89ebe1d6ef10c293b94175a243a2d9442c163d9944" +dependencies = [ + "itoa 1.0.1", + "ryu", + "serde", +] + +[[package]] +name = "serde_stacker" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142e02b5fb4b5602a71c7f0e96120e4371abb3f0c0639511b829c3537f498c12" +dependencies = [ + "serde", + "stacker", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa 1.0.1", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" +dependencies = [ + "sha1_smol", +] + +[[package]] +name = "sha1_smol" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" + +[[package]] +name = "sha2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a256f46ea78a0c0d9ff00077504903ac881a1dafdc20da66545699e7776b3e69" +dependencies = [ + "block-buffer 0.7.3", + "digest 0.8.1", + "fake-simd", + "opaque-debug 0.2.3", +] + +[[package]] +name = "sha2" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if", + "cpufeatures", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + +[[package]] +name = "sha2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest 0.10.6", +] + +[[package]] +name = "sha2-asm" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c2f225be6502f2134e6bbb35bb5e2957e41ffa0495ed08bce2e2b4ca885da4" +dependencies = [ + "cc", +] + +[[package]] +name = "sha3" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f81199417d4e5de3f04b1e871023acea7389672c4135918f05aa9cbf2f2fa809" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "keccak", + "opaque-debug 0.3.0", +] + +[[package]] +name = "sha3" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdf0c33fae925bdc080598b84bc15c55e7b9a4a43b3c704da051f977469691c9" +dependencies = [ + "digest 0.10.6", + "keccak", +] + +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" +dependencies = [ + "libc", +] + +[[package]] +name = "slab" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32" + +[[package]] +name = "slog" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8347046d4ebd943127157b94d63abb990fcf729dc4e9978927fdf4ac3c998d06" + +[[package]] +name = "slog-async" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "766c59b252e62a34651412870ff55d8c4e6d04df19b43eecb2703e417b097ffe" +dependencies = [ + "crossbeam-channel", + "slog", + "take_mut", + "thread_local", +] + +[[package]] +name = "slog-atomic" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b517f2dda9e1458733eb8350bad1a3632ffed8141be4c0f3d6def899a9b066" +dependencies = [ + "arc-swap", + "slog", +] + +[[package]] +name = "slog-json" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e1e53f61af1e3c8b852eef0a9dee29008f55d6dd63794f3f12cef786cf0f219" +dependencies = [ + "serde", + "serde_json", + "slog", + "time 0.3.17", +] + +[[package]] +name = "slog-scope" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f95a4b4c3274cd2869549da82b57ccc930859bdbf5bcea0424bc5f140b3c786" +dependencies = [ + "arc-swap", + "lazy_static", + "slog", +] + +[[package]] +name = "slog-term" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87d29185c55b7b258b4f120eab00f48557d4d9bc814f41713f449d35b0f8977c" +dependencies = [ + "atty", + "slog", + "term 0.7.0", + "thread_local", + "time 0.3.17", +] + +[[package]] +name = "smallvec" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" + +[[package]] +name = "socket2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "spin" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c530c2b0d0bf8b69304b39fe2001993e267461948b890cd037d8ad4293fa1a0d" + +[[package]] +name = "stable-pattern" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4564168c00635f88eaed410d5efa8131afa8d8699a612c80c455a0ba05c21045" +dependencies = [ + "memchr", +] + +[[package]] +name = "stacker" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "winapi", +] + +[[package]] +name = "stacks-common" +version = "0.0.1" +source = "git+https://github.com/stacks-network/stacks-blockchain.git?rev=601ac7a0b4ed3de027382a33560d079aaa337b4d#601ac7a0b4ed3de027382a33560d079aaa337b4d" +dependencies = [ + "chrono", + "curve25519-dalek", + "ed25519-dalek", + "lazy_static", + "libc", + "percent-encoding", + "rand 0.7.3", + "ripemd", + "rusqlite", + "secp256k1 0.21.3", + "serde", + "serde_derive", + "serde_json", + "sha2 0.10.6", + "sha3 0.10.6", + "time 0.2.27", +] + +[[package]] +name = "stacks-rpc-client" +version = "1.0.0" +dependencies = [ + "clarinet-utils", + "clarity-repl", + "reqwest", + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "standback" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" +dependencies = [ + "version_check", +] + +[[package]] +name = "state" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbe866e1e51e8260c9eed836a042a5e7f6726bb2b411dffeaa712e19c388f23b" +dependencies = [ + "loom", +] + +[[package]] +name = "stdweb" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" +dependencies = [ + "discard", + "rustc_version 0.2.3", + "stdweb-derive", + "stdweb-internal-macros", + "stdweb-internal-runtime", + "wasm-bindgen", +] + +[[package]] +name = "stdweb-derive" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "serde_derive", + "syn", +] + +[[package]] +name = "stdweb-internal-macros" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" +dependencies = [ + "base-x", + "proc-macro2", + "quote", + "serde", + "serde_derive", + "serde_json", + "sha1", + "syn", +] + +[[package]] +name = "stdweb-internal-runtime" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" + +[[package]] +name = "str-buf" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44a3643b4ff9caf57abcee9c2c621d6c03d9135e0d8b589bd9afb5992cb176a" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "strum" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae14b91c7d11c9a851d3fbc80a963198998c2a64eec840477fa92d8ce9b70bb" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38" +dependencies = [ + "heck 0.3.3", + "proc-macro2", + "quote", + "rustversion", + "syn", +] + +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + +[[package]] +name = "syn" +version = "1.0.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "take_mut" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60" + +[[package]] +name = "tempfile" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" +dependencies = [ + "cfg-if", + "fastrand", + "libc", + "redox_syscall 0.2.13", + "remove_dir_all", + "winapi", +] + +[[package]] +name = "term" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd106a334b7657c10b7c540a0106114feadeb4dc314513e97df481d5d966f42" +dependencies = [ + "byteorder", + "dirs", + "winapi", +] + +[[package]] +name = "term" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f" +dependencies = [ + "dirs-next", + "rustversion", + "winapi", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "textwrap" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" + +[[package]] +name = "thiserror" +version = "1.0.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" +dependencies = [ + "once_cell", +] + +[[package]] +name = "time" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", +] + +[[package]] +name = "time" +version = "0.2.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" +dependencies = [ + "const_fn", + "libc", + "standback", + "stdweb", + "time-macros 0.1.1", + "version_check", + "winapi", +] + +[[package]] +name = "time" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376" +dependencies = [ + "itoa 1.0.1", + "libc", + "num_threads", + "serde", + "time-core", + "time-macros 0.2.6", +] + +[[package]] +name = "time-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" + +[[package]] +name = "time-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" +dependencies = [ + "proc-macro-hack", + "time-macros-impl", +] + +[[package]] +name = "time-macros" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2" +dependencies = [ + "time-core", +] + +[[package]] +name = "time-macros-impl" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote", + "standback", + "syn", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + +[[package]] +name = "tokio" +version = "1.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae" +dependencies = [ + "autocfg", + "bytes", + "libc", + "memchr", + "mio", + "num_cpus", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.42.0", +] + +[[package]] +name = "tokio-macros" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b557f72f448c511a979e2564e55d74e6c4432fc96ff4f6241bc6bded342643b7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.23.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4151fda0cf2798550ad0b34bcfc9b9dcc2a9d2471c895c68f3a8818e54f2389e" +dependencies = [ + "rustls", + "tokio", + "webpki", +] + +[[package]] +name = "tokio-stream" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50145484efff8818b5ccd256697f36863f587da82cf8b409c53adf1e840798e3" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e99e1983e5d376cd8eb4b66604d2e99e79f5bd988c3055891dcd8c9e2604cc0" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "log", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0edfdeb067411dba2044da6d1cb2df793dd35add7888d73c16e3381ded401764" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "indexmap", + "serde", +] + +[[package]] +name = "tower-service" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" + +[[package]] +name = "tracing" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" +dependencies = [ + "lazy_static", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +dependencies = [ + "lazy_static", + "log", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bc28f93baff38037f64e6f43d34cfa1605f27a49c34e8a04c5e78b0babf2596" +dependencies = [ + "ansi_term", + "lazy_static", + "matchers", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" + +[[package]] +name = "typenum" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" + +[[package]] +name = "ubyte" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42756bb9e708855de2f8a98195643dff31a97f0485d90d8467b39dc24be9e8fe" +dependencies = [ + "serde", +] + +[[package]] +name = "ucd-trie" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" + +[[package]] +name = "uncased" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baeed7327e25054889b9bd4f975f32e5f4c5d434042d59ab6cd4142c0a76ed0" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" + +[[package]] +name = "unicode-normalization" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-segmentation" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99" + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "unicode-xid" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" + +[[package]] +name = "universal-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d3160b73c9a19f7e2939a2fdad446c57c1bbbbf4d919d3213ff1267a580d8b5" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "url" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" +dependencies = [ + "form_urlencoded", + "idna", + "matches", + "percent-encoding", +] + +[[package]] +name = "utf8parse" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936e4b492acfd135421d8dca4b1aa80a7bfc26e702ef3af710e0752684df5372" + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "want" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +dependencies = [ + "log", + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f741de44b75e14c35df886aff5f1eb73aa114fa5d4d00dcd37b5e01259bf3b2" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" + +[[package]] +name = "web-sys" +version = "0.3.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "webpki-roots" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d8de8415c823c8abd270ad483c6feeac771fad964890779f9a8cb24fbbc1bf" +dependencies = [ + "webpki", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "030b7ff91626e57a05ca64a07c481973cbb2db774e4852c9c7ca342408c6a99a" +dependencies = [ + "windows_aarch64_msvc 0.30.0", + "windows_i686_gnu 0.30.0", + "windows_i686_msvc 0.30.0", + "windows_x86_64_gnu 0.30.0", + "windows_x86_64_msvc 0.30.0", +] + +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc 0.36.1", + "windows_i686_gnu 0.36.1", + "windows_i686_msvc 0.36.1", + "windows_x86_64_gnu 0.36.1", + "windows_x86_64_msvc 0.36.1", +] + +[[package]] +name = "windows-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc 0.42.0", + "windows_i686_gnu 0.42.0", + "windows_i686_msvc 0.42.0", + "windows_x86_64_gnu 0.42.0", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc 0.42.0", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29277a4435d642f775f63c7d1faeb927adba532886ce0287bd985bffb16b6bca" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" + +[[package]] +name = "windows_i686_gnu" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1145e1989da93956c68d1864f32fb97c8f561a8f89a5125f6a2b7ea75524e4b8" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" + +[[package]] +name = "windows_i686_msvc" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a09e3a0d4753b73019db171c1339cd4362c8c44baf1bcea336235e955954a6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca64fcb0220d58db4c119e050e7af03c69e6f4f415ef69ec1773d9aab422d5a" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08cabc9f0066848fef4bc6a1c1668e6efce38b661d2aeec75d18d8617eebb5f1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + +[[package]] +name = "yansi" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" + +[[package]] +name = "zeroize" +version = "1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f" diff --git a/components/chainhook-event-observer/Cargo.toml b/components/chainhook-event-observer/Cargo.toml new file mode 100644 index 0000000..2ab9738 --- /dev/null +++ b/components/chainhook-event-observer/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "chainhook-event-observer" +version = "1.0.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde = "1" +serde_json = { version = "1", features = ["arbitrary_precision"] } +serde_derive = "1" +stacks_rpc_client = { package = "stacks-rpc-client", path = "../../components/stacks-rpc-client" } +clarinet_utils = { package = "clarinet-utils", path = "../../components/clarinet-utils" } +clarity_repl = { package = "clarity-repl", path = "../../components/clarity-repl" } +hiro_system_kit = { package = "hiro-system-kit", path = "../../components/hiro-system-kit" } + +chainhook_types = { package = "chainhook-types", path = "../chainhook-types-rs" } +rocket = { version = "=0.5.0-rc.2", features = ["json"] } +bitcoincore-rpc = "0.16.0" +bitcoincore-rpc-json = "0.16.0" +base64 = "0.13.0" +reqwest = { version = "0.11", default-features = false, features = [ + "blocking", + "json", + "rustls-tls", +] } +tokio = { version = "1.24", features = ["full"] } +base58 = "0.2.0" +clap = { version = "3.1.6", features = ["derive"], optional = true } +clap_generate = { version = "3.0.3", optional = true } +toml = { version = "0.5.6", features = ["preserve_order"], optional = true } +ctrlc = { version = "3.2.2", optional = true } +schemars = { version = "0.8.10" } +rocket_okapi = "0.8.0-rc.1" +crossbeam-channel = "0.5.6" + +[features] +default = ["cli"] +log = ["hiro_system_kit/log"] +cli = ["clap", "clap_generate", "toml", "ctrlc", "log"] diff --git a/components/chainhook-event-observer/Observer.toml b/components/chainhook-event-observer/Observer.toml new file mode 100644 index 0000000..4b71112 --- /dev/null +++ b/components/chainhook-event-observer/Observer.toml @@ -0,0 +1,14 @@ +normalization_enabled = true +bitcoin_rpc_proxy_enabled = false +grpc_server_enabled = true +hooks_enabled = true +webhooks = [] +control_port = 20446 +ingestion_port = 20445 +bitcoin_node_username = "devnet" +bitcoin_node_password = "devnet" +bitcoin_node_rpc_host = "localhost" +bitcoin_node_rpc_port = 18443 +stacks_node_rpc_host = "localhost" +stacks_node_rpc_port = 20443 +operators = ["74738ff5-5367-5958-9aee-98fffdcd1876"] \ No newline at end of file diff --git a/components/chainhook-event-observer/doc/openapi.json b/components/chainhook-event-observer/doc/openapi.json new file mode 100644 index 0000000..db64945 --- /dev/null +++ b/components/chainhook-event-observer/doc/openapi.json @@ -0,0 +1,682 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "chainhook-event-observer", + "version": "0.1.0" + }, + "paths": { + "/v1/chainhooks": { + "post": { + "tags": [ + "Chainhooks" + ], + "operationId": "handle_create_hook", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChainhookSpecification" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/v1/chainhooks/bitcoin/{hook_uuid}": { + "delete": { + "tags": [ + "Chainhooks" + ], + "operationId": "handle_delete_bitcoin_hook", + "parameters": [ + { + "name": "hook_uuid", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/v1/chainhooks/stacks/{hook_uuid}": { + "delete": { + "tags": [ + "Chainhooks" + ], + "operationId": "handle_delete_stacks_hook", + "parameters": [ + { + "name": "hook_uuid", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + } + }, + "components": { + "schemas": { + "ChainhookSpecification": { + "oneOf": [ + { + "type": "object", + "required": [ + "bitcoin" + ], + "properties": { + "bitcoin": { + "$ref": "#/components/schemas/BitcoinChainhookSpecification" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "stacks" + ], + "properties": { + "stacks": { + "$ref": "#/components/schemas/StacksChainhookSpecification" + } + }, + "additionalProperties": false + } + ] + }, + "BitcoinChainhookSpecification": { + "type": "object", + "required": [ + "action", + "name", + "network", + "predicate", + "uuid", + "version" + ], + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "network": { + "$ref": "#/components/schemas/BitcoinNetwork" + }, + "version": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "start_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0, + "nullable": true + }, + "end_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0, + "nullable": true + }, + "predicate": { + "$ref": "#/components/schemas/BitcoinHookPredicate" + }, + "action": { + "$ref": "#/components/schemas/HookAction" + } + } + }, + "BitcoinNetwork": { + "type": "string", + "enum": [ + "regtest", + "testnet", + "mainnet" + ] + }, + "BitcoinHookPredicate": { + "type": "object", + "oneOf": [ + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "hex" + ] + }, + "rule": { + "$ref": "#/components/schemas/MatchingRule" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "p2pkh" + ] + }, + "rule": { + "$ref": "#/components/schemas/MatchingRule" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "p2sh" + ] + }, + "rule": { + "$ref": "#/components/schemas/MatchingRule" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "p2wpkh" + ] + }, + "rule": { + "$ref": "#/components/schemas/MatchingRule" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "p2wsh" + ] + }, + "rule": { + "$ref": "#/components/schemas/MatchingRule" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "script" + ] + }, + "rule": { + "$ref": "#/components/schemas/ScriptTemplate" + } + } + } + ], + "required": [ + "scope" + ], + "properties": { + "scope": { + "$ref": "#/components/schemas/Scope" + } + } + }, + "Scope": { + "type": "string", + "enum": [ + "inputs", + "outputs" + ] + }, + "MatchingRule": { + "oneOf": [ + { + "type": "object", + "required": [ + "equals" + ], + "properties": { + "equals": { + "type": "string" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "starts_with" + ], + "properties": { + "starts_with": { + "type": "string" + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "ends_with" + ], + "properties": { + "ends_with": { + "type": "string" + } + }, + "additionalProperties": false + } + ] + }, + "ScriptTemplate": { + "type": "object", + "required": [ + "instructions" + ], + "properties": { + "instructions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ScriptInstruction" + } + } + } + }, + "ScriptInstruction": { + "oneOf": [ + { + "type": "object", + "required": [ + "opcode" + ], + "properties": { + "opcode": { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "raw_bytes" + ], + "properties": { + "raw_bytes": { + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + } + } + }, + "additionalProperties": false + }, + { + "type": "object", + "required": [ + "placeholder" + ], + "properties": { + "placeholder": { + "type": "array", + "items": [ + { + "type": "string" + }, + { + "type": "integer", + "format": "uint8", + "minimum": 0.0 + } + ], + "maxItems": 2, + "minItems": 2 + } + }, + "additionalProperties": false + } + ] + }, + "HookAction": { + "oneOf": [ + { + "type": "object", + "required": [ + "http" + ], + "properties": { + "http": { + "$ref": "#/components/schemas/HttpHook" + } + }, + "additionalProperties": false + } + ] + }, + "HttpHook": { + "type": "object", + "required": [ + "authorization_header", + "method", + "url" + ], + "properties": { + "url": { + "type": "string" + }, + "method": { + "type": "string" + }, + "authorization_header": { + "type": "string" + } + } + }, + "StacksChainhookSpecification": { + "type": "object", + "required": [ + "action", + "name", + "network", + "predicate", + "uuid", + "version" + ], + "properties": { + "uuid": { + "type": "string" + }, + "name": { + "type": "string" + }, + "network": { + "$ref": "#/components/schemas/StacksNetwork" + }, + "version": { + "type": "integer", + "format": "uint32", + "minimum": 0.0 + }, + "start_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0, + "nullable": true + }, + "end_block": { + "type": "integer", + "format": "uint64", + "minimum": 0.0, + "nullable": true + }, + "predicate": { + "$ref": "#/components/schemas/StacksTransactionFilterPredicate" + }, + "action": { + "$ref": "#/components/schemas/HookAction" + } + } + }, + "StacksNetwork": { + "type": "string", + "enum": [ + "simnet", + "devnet", + "testnet", + "mainnet" + ] + }, + "StacksTransactionFilterPredicate": { + "oneOf": [ + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "contract_call" + ] + }, + "rule": { + "$ref": "#/components/schemas/StacksContractCallBasedPredicate" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "print_event" + ] + }, + "rule": { + "$ref": "#/components/schemas/StacksPrintEventBasedPredicate" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "ft_event" + ] + }, + "rule": { + "$ref": "#/components/schemas/StacksFtEventBasedPredicate" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "nft_event" + ] + }, + "rule": { + "$ref": "#/components/schemas/StacksNftEventBasedPredicate" + } + } + }, + { + "type": "object", + "required": [ + "rule", + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "stx_event" + ] + }, + "rule": { + "$ref": "#/components/schemas/StacksStxEventBasedPredicate" + } + } + } + ] + }, + "StacksContractCallBasedPredicate": { + "type": "object", + "required": [ + "contract_identifier", + "method" + ], + "properties": { + "contract_identifier": { + "type": "string" + }, + "method": { + "type": "string" + } + } + }, + "StacksPrintEventBasedPredicate": { + "type": "object", + "required": [ + "contains", + "contract_identifier" + ], + "properties": { + "contract_identifier": { + "type": "string" + }, + "contains": { + "type": "string" + } + } + }, + "StacksFtEventBasedPredicate": { + "type": "object", + "required": [ + "actions", + "asset_identifier" + ], + "properties": { + "asset_identifier": { + "type": "string" + }, + "actions": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "StacksNftEventBasedPredicate": { + "type": "object", + "required": [ + "actions", + "asset_identifier" + ], + "properties": { + "asset_identifier": { + "type": "string" + }, + "actions": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "StacksStxEventBasedPredicate": { + "type": "object", + "required": [ + "actions" + ], + "properties": { + "actions": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } \ No newline at end of file diff --git a/components/chainhook-event-observer/src/chainhooks/bitcoin/mod.rs b/components/chainhook-event-observer/src/chainhooks/bitcoin/mod.rs new file mode 100644 index 0000000..4624390 --- /dev/null +++ b/components/chainhook-event-observer/src/chainhooks/bitcoin/mod.rs @@ -0,0 +1,398 @@ +use super::types::{ + BitcoinChainhookSpecification, BitcoinPredicateType, ExactMatchingRule, HookAction, + KeyRegistrationPredicate, LockSTXPredicate, MatchingRule, PobPredicate, PoxPredicate, + TransferSTXPredicate, +}; +use base58::FromBase58; +use bitcoincore_rpc::bitcoin::blockdata::opcodes; +use bitcoincore_rpc::bitcoin::blockdata::script::Builder as BitcoinScriptBuilder; +use bitcoincore_rpc::bitcoin::util::address::Payload; +use bitcoincore_rpc::bitcoin::Address; +use chainhook_types::{ + BitcoinBlockData, BitcoinChainEvent, BitcoinTransactionData, StacksBaseChainOperation, + TransactionIdentifier, +}; +use clarity_repl::clarity::util::hash::to_hex; +use reqwest::{Client, Method}; +use serde_json::Value as JsonValue; +use std::collections::HashMap; +use std::str::FromStr; + +use reqwest::RequestBuilder; + +pub struct BitcoinTriggerChainhook<'a> { + pub chainhook: &'a BitcoinChainhookSpecification, + pub apply: Vec<(Vec<&'a BitcoinTransactionData>, &'a BitcoinBlockData)>, + pub rollback: Vec<(Vec<&'a BitcoinTransactionData>, &'a BitcoinBlockData)>, +} + +#[derive(Clone, Debug)] +pub struct BitcoinApplyTransactionPayload { + pub block: BitcoinBlockData, +} + +#[derive(Clone, Debug)] +pub struct BitcoinRollbackTransactionPayload { + pub block: BitcoinBlockData, +} + +#[derive(Clone, Debug)] +pub struct BitcoinChainhookPayload { + pub uuid: String, +} + +#[derive(Clone, Debug)] +pub struct BitcoinChainhookOccurrencePayload { + pub apply: Vec, + pub rollback: Vec, + pub chainhook: BitcoinChainhookPayload, +} + +pub enum BitcoinChainhookOccurrence { + Http(RequestBuilder), + File(String, Vec), + Data(BitcoinChainhookOccurrencePayload), +} + +pub fn evaluate_bitcoin_chainhooks_on_chain_event<'a>( + chain_event: &'a BitcoinChainEvent, + active_chainhooks: Vec<&'a BitcoinChainhookSpecification>, +) -> Vec> { + let mut triggered_chainhooks = vec![]; + match chain_event { + BitcoinChainEvent::ChainUpdatedWithBlocks(event) => { + for chainhook in active_chainhooks.iter() { + let mut apply = vec![]; + let rollback = vec![]; + + for block in event.new_blocks.iter() { + let mut hits = vec![]; + for tx in block.transactions.iter() { + if chainhook.evaluate_transaction_predicate(&tx) { + hits.push(tx); + } + } + if hits.len() > 0 { + apply.push((hits, block)); + } + } + + if !apply.is_empty() { + triggered_chainhooks.push(BitcoinTriggerChainhook { + chainhook, + apply, + rollback, + }) + } + } + } + BitcoinChainEvent::ChainUpdatedWithReorg(event) => { + for chainhook in active_chainhooks.iter() { + let mut apply = vec![]; + let mut rollback = vec![]; + + for block in event.blocks_to_apply.iter() { + let mut hits = vec![]; + for tx in block.transactions.iter() { + if chainhook.evaluate_transaction_predicate(&tx) { + hits.push(tx); + } + } + if hits.len() > 0 { + apply.push((hits, block)); + } + } + for block in event.blocks_to_rollback.iter() { + let mut hits = vec![]; + for tx in block.transactions.iter() { + if chainhook.evaluate_transaction_predicate(&tx) { + hits.push(tx); + } + } + if hits.len() > 0 { + rollback.push((hits, block)); + } + } + if !apply.is_empty() || !rollback.is_empty() { + triggered_chainhooks.push(BitcoinTriggerChainhook { + chainhook, + apply, + rollback, + }) + } + } + } + } + triggered_chainhooks +} + +pub fn serialize_bitcoin_payload_to_json<'a>( + trigger: BitcoinTriggerChainhook<'a>, + proofs: &HashMap<&'a TransactionIdentifier, String>, +) -> JsonValue { + json!({ + "apply": trigger.apply.into_iter().map(|(transactions, block)| { + json!({ + "block_identifier": block.block_identifier, + "parent_block_identifier": block.parent_block_identifier, + "timestamp": block.timestamp, + "transactions": transactions.into_iter().map(|transaction| { + json!({ + "transaction_identifier": transaction.transaction_identifier, + "operations": transaction.operations, + "metadata": json!({ + "inputs": transaction.metadata.inputs, + "outputs": transaction.metadata.outputs, + "stacks_operations": transaction.metadata.stacks_operations, + "proof": proofs.get(&transaction.transaction_identifier), + }), + }) + }).collect::>(), + "metadata": block.metadata, + }) + }).collect::>(), + "rollback": trigger.rollback.into_iter().map(|(transactions, block)| { + json!({ + "block_identifier": block.block_identifier, + "parent_block_identifier": block.parent_block_identifier, + "timestamp": block.timestamp, + "transactions": transactions, + "metadata": block.metadata, + }) + }).collect::>(), + "chainhook": { + "uuid": trigger.chainhook.uuid, + "predicate": trigger.chainhook.predicate, + } + }) +} + +pub fn handle_bitcoin_hook_action<'a>( + trigger: BitcoinTriggerChainhook<'a>, + proofs: &HashMap<&'a TransactionIdentifier, String>, +) -> Option { + match &trigger.chainhook.action { + HookAction::Http(http) => { + let client = Client::builder().build().unwrap(); + let host = format!("{}", http.url); + let method = Method::from_bytes(http.method.as_bytes()).unwrap(); + let body = + serde_json::to_vec(&serialize_bitcoin_payload_to_json(trigger, proofs)).unwrap(); + Some(BitcoinChainhookOccurrence::Http( + client + .request(method, &host) + .header("Content-Type", "application/json") + .header("Authorization", http.authorization_header.clone()) + .body(body), + )) + } + HookAction::File(disk) => { + let bytes = + serde_json::to_vec(&serialize_bitcoin_payload_to_json(trigger, proofs)).unwrap(); + Some(BitcoinChainhookOccurrence::File( + disk.path.to_string(), + bytes, + )) + } + HookAction::Noop => Some(BitcoinChainhookOccurrence::Data( + BitcoinChainhookOccurrencePayload { + apply: trigger + .apply + .into_iter() + .map(|(transactions, block)| { + let mut block = block.clone(); + block.transactions = transactions + .into_iter() + .map(|t| t.clone()) + .collect::>(); + BitcoinApplyTransactionPayload { block } + }) + .collect::>(), + rollback: trigger + .rollback + .into_iter() + .map(|(transactions, block)| { + let mut block = block.clone(); + block.transactions = transactions + .into_iter() + .map(|t| t.clone()) + .collect::>(); + BitcoinRollbackTransactionPayload { block } + }) + .collect::>(), + chainhook: BitcoinChainhookPayload { + uuid: trigger.chainhook.uuid.clone(), + }, + }, + )), + } +} + +impl BitcoinChainhookSpecification { + pub fn evaluate_transaction_predicate(&self, tx: &BitcoinTransactionData) -> bool { + // TODO(lgalabru): follow-up on this implementation + match &self.predicate.kind { + BitcoinPredicateType::TransactionIdentifierHash(ExactMatchingRule::Equals(txid)) => { + tx.transaction_identifier.hash.eq(txid) + } + BitcoinPredicateType::OpReturn(MatchingRule::Equals(hex_bytes)) => { + for output in tx.metadata.outputs.iter() { + if output.script_pubkey.eq(hex_bytes) { + return true; + } + } + false + } + BitcoinPredicateType::OpReturn(MatchingRule::StartsWith(hex_bytes)) => { + for output in tx.metadata.outputs.iter() { + if output.script_pubkey.starts_with(hex_bytes) { + return true; + } + } + false + } + BitcoinPredicateType::OpReturn(MatchingRule::EndsWith(hex_bytes)) => { + for output in tx.metadata.outputs.iter() { + if output.script_pubkey.ends_with(hex_bytes) { + return true; + } + } + false + } + BitcoinPredicateType::P2pkh(ExactMatchingRule::Equals(address)) => { + let pubkey_hash = address + .from_base58() + .expect("Unable to get bytes from btc address"); + let script = BitcoinScriptBuilder::new() + .push_opcode(opcodes::all::OP_DUP) + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&pubkey_hash[1..21]) + .push_opcode(opcodes::all::OP_EQUALVERIFY) + .push_opcode(opcodes::all::OP_CHECKSIG) + .into_script(); + + for output in tx.metadata.outputs.iter() { + if output.script_pubkey == to_hex(script.as_bytes()) { + return true; + } + } + false + } + BitcoinPredicateType::P2sh(ExactMatchingRule::Equals(address)) => { + let script_hash = address + .from_base58() + .expect("Unable to get bytes from btc address"); + let script = BitcoinScriptBuilder::new() + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&script_hash[1..21]) + .push_opcode(opcodes::all::OP_EQUAL) + .into_script(); + + for output in tx.metadata.outputs.iter() { + if output.script_pubkey == to_hex(script.as_bytes()) { + return true; + } + } + false + } + BitcoinPredicateType::P2wpkh(ExactMatchingRule::Equals(encoded_address)) + | BitcoinPredicateType::P2wsh(ExactMatchingRule::Equals(encoded_address)) => { + let address = match Address::from_str(encoded_address) { + Ok(address) => match address.payload { + Payload::WitnessProgram { + version: _, + program: _, + } => address, + _ => return false, + }, + Err(_) => return false, + }; + let script_bytes = to_hex(address.script_pubkey().as_bytes()); + for output in tx.metadata.outputs.iter() { + if output.script_pubkey == script_bytes { + return true; + } + } + false + } + BitcoinPredicateType::Pob(PobPredicate::Any) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::PobBlockCommitment(_) = op { + return true; + } + } + false + } + BitcoinPredicateType::Pox(PoxPredicate::Any) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::PoxBlockCommitment(_) = op { + return true; + } + } + false + } + BitcoinPredicateType::Pox(PoxPredicate::Recipient(MatchingRule::Equals(address))) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::PoxBlockCommitment(commitment) = op { + for reward in commitment.rewards.iter() { + if reward.recipient.eq(address) { + return true; + } + } + } + } + false + } + BitcoinPredicateType::Pox(PoxPredicate::Recipient(MatchingRule::StartsWith( + prefix, + ))) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::PoxBlockCommitment(commitment) = op { + for reward in commitment.rewards.iter() { + if reward.recipient.starts_with(prefix) { + return true; + } + } + } + } + false + } + BitcoinPredicateType::Pox(PoxPredicate::Recipient(MatchingRule::EndsWith(suffix))) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::PoxBlockCommitment(commitment) = op { + for reward in commitment.rewards.iter() { + if reward.recipient.ends_with(suffix) { + return true; + } + } + } + } + false + } + BitcoinPredicateType::KeyRegistration(KeyRegistrationPredicate::Any) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::KeyRegistration(_) = op { + return true; + } + } + false + } + BitcoinPredicateType::TransferSTX(TransferSTXPredicate::Any) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::TransferSTX(_) = op { + return true; + } + } + false + } + BitcoinPredicateType::LockSTX(LockSTXPredicate::Any) => { + for op in tx.metadata.stacks_operations.iter() { + if let StacksBaseChainOperation::LockSTX(_) = op { + return true; + } + } + false + } + } + } +} diff --git a/components/chainhook-event-observer/src/chainhooks/mod.rs b/components/chainhook-event-observer/src/chainhooks/mod.rs new file mode 100644 index 0000000..0eeb2f2 --- /dev/null +++ b/components/chainhook-event-observer/src/chainhooks/mod.rs @@ -0,0 +1,3 @@ +pub mod bitcoin; +pub mod stacks; +pub mod types; diff --git a/components/chainhook-event-observer/src/chainhooks/stacks/mod.rs b/components/chainhook-event-observer/src/chainhooks/stacks/mod.rs new file mode 100644 index 0000000..00b3f55 --- /dev/null +++ b/components/chainhook-event-observer/src/chainhooks/stacks/mod.rs @@ -0,0 +1,694 @@ +use crate::utils::{AbstractStacksBlock, Context}; + +use super::types::{ + HookAction, StacksChainhookSpecification, StacksContractDeploymentPredicate, + StacksTransactionFilterPredicate, +}; +use chainhook_types::{ + BlockIdentifier, StacksChainEvent, StacksTransactionData, StacksTransactionEvent, + StacksTransactionKind, TransactionIdentifier, +}; +use clarity_repl::clarity::codec::StacksMessageCodec; +use clarity_repl::clarity::util::hash::hex_bytes; +use clarity_repl::clarity::vm::types::{CharType, SequenceData, Value as ClarityValue}; +use hiro_system_kit::slog; +use reqwest::{Client, Method}; +use serde_json::Value as JsonValue; +use std::collections::HashMap; +use std::io::Cursor; + +use reqwest::RequestBuilder; + +pub struct StacksTriggerChainhook<'a> { + pub chainhook: &'a StacksChainhookSpecification, + pub apply: Vec<(Vec<&'a StacksTransactionData>, &'a dyn AbstractStacksBlock)>, + pub rollback: Vec<(Vec<&'a StacksTransactionData>, &'a dyn AbstractStacksBlock)>, +} + +#[derive(Clone, Debug)] +pub struct StacksApplyTransactionPayload { + pub block_identifier: BlockIdentifier, + pub transactions: Vec, +} + +#[derive(Clone, Debug)] +pub struct StacksRollbackTransactionPayload { + pub block_identifier: BlockIdentifier, + pub transactions: Vec, +} + +#[derive(Clone, Debug)] +pub struct StacksChainhookPayload { + pub uuid: String, +} + +#[derive(Clone, Debug)] +pub struct StacksChainhookOccurrencePayload { + pub apply: Vec, + pub rollback: Vec, + pub chainhook: StacksChainhookPayload, +} +pub enum StacksChainhookOccurrence { + Http(RequestBuilder), + File(String, Vec), + Data(StacksChainhookOccurrencePayload), +} + +impl<'a> StacksTriggerChainhook<'a> { + pub fn should_decode_clarity_value(&self) -> bool { + self.chainhook.decode_clarity_values.unwrap_or(false) + } +} + +pub fn evaluate_stacks_chainhooks_on_chain_event<'a>( + chain_event: &'a StacksChainEvent, + active_chainhooks: Vec<&'a StacksChainhookSpecification>, + ctx: &Context, +) -> Vec> { + let mut triggered_chainhooks = vec![]; + match chain_event { + StacksChainEvent::ChainUpdatedWithBlocks(update) => { + for chainhook in active_chainhooks.iter() { + let mut apply = vec![]; + let mut rollback = vec![]; + for block_update in update.new_blocks.iter() { + for parents_microblock_to_apply in + block_update.parent_microblocks_to_apply.iter() + { + apply.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![parents_microblock_to_apply], + chainhook, + ctx, + )); + } + for parents_microblock_to_rolllback in + block_update.parent_microblocks_to_rollback.iter() + { + rollback.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![parents_microblock_to_rolllback], + chainhook, + ctx, + )); + } + apply.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![&block_update.block], + chainhook, + ctx, + )); + } + if !apply.is_empty() || !rollback.is_empty() { + triggered_chainhooks.push(StacksTriggerChainhook { + chainhook, + apply, + rollback, + }) + } + } + } + StacksChainEvent::ChainUpdatedWithMicroblocks(update) => { + for chainhook in active_chainhooks.iter() { + let mut apply = vec![]; + let rollback = vec![]; + + for microblock_to_apply in update.new_microblocks.iter() { + apply.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![microblock_to_apply], + chainhook, + ctx, + )); + } + if !apply.is_empty() || !rollback.is_empty() { + triggered_chainhooks.push(StacksTriggerChainhook { + chainhook, + apply, + rollback, + }) + } + } + } + StacksChainEvent::ChainUpdatedWithMicroblocksReorg(update) => { + for chainhook in active_chainhooks.iter() { + let mut apply = vec![]; + let mut rollback = vec![]; + + for microblock_to_apply in update.microblocks_to_apply.iter() { + apply.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![microblock_to_apply], + chainhook, + ctx, + )); + } + for microblock_to_rollback in update.microblocks_to_rollback.iter() { + rollback.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![microblock_to_rollback], + chainhook, + ctx, + )); + } + if !apply.is_empty() || !rollback.is_empty() { + triggered_chainhooks.push(StacksTriggerChainhook { + chainhook, + apply, + rollback, + }) + } + } + } + StacksChainEvent::ChainUpdatedWithReorg(update) => { + for chainhook in active_chainhooks.iter() { + let mut apply = vec![]; + let mut rollback = vec![]; + + for block_update in update.blocks_to_apply.iter() { + for parents_microblock_to_apply in + block_update.parent_microblocks_to_apply.iter() + { + apply.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![parents_microblock_to_apply], + chainhook, + ctx, + )); + } + apply.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![&block_update.block], + chainhook, + ctx, + )); + } + for block_update in update.blocks_to_rollback.iter() { + for parents_microblock_to_rollback in + block_update.parent_microblocks_to_rollback.iter() + { + rollback.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![parents_microblock_to_rollback], + chainhook, + ctx, + )); + } + rollback.append(&mut evaluate_stacks_chainhook_on_blocks( + vec![&block_update.block], + chainhook, + ctx, + )); + } + if !apply.is_empty() || !rollback.is_empty() { + triggered_chainhooks.push(StacksTriggerChainhook { + chainhook, + apply, + rollback, + }) + } + } + } + } + triggered_chainhooks +} + +fn evaluate_stacks_chainhook_on_blocks<'a>( + blocks: Vec<&'a dyn AbstractStacksBlock>, + chainhook: &'a StacksChainhookSpecification, + ctx: &Context, +) -> Vec<(Vec<&'a StacksTransactionData>, &'a dyn AbstractStacksBlock)> { + let mut occurrences = vec![]; + for block in blocks { + let mut hits = vec![]; + for tx in block.get_transactions().iter() { + if evaluate_stacks_transaction_predicate_on_transaction(tx, chainhook, ctx) { + hits.push(tx); + } + } + if hits.len() > 0 { + occurrences.push((hits, block)); + } + } + occurrences +} + +pub fn evaluate_stacks_transaction_predicate_on_transaction<'a>( + transaction: &'a StacksTransactionData, + chainhook: &'a StacksChainhookSpecification, + ctx: &Context, +) -> bool { + match &chainhook.transaction_predicate { + StacksTransactionFilterPredicate::ContractDeployment( + StacksContractDeploymentPredicate::Principal(expected_deployer), + ) => match &transaction.metadata.kind { + StacksTransactionKind::ContractDeployment(actual_deployment) => actual_deployment + .contract_identifier + .starts_with(expected_deployer), + _ => false, + }, + StacksTransactionFilterPredicate::ContractDeployment( + StacksContractDeploymentPredicate::Trait(_expected_trait), + ) => match &transaction.metadata.kind { + StacksTransactionKind::ContractDeployment(_actual_deployment) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "StacksContractDeploymentPredicate::Trait uninmplemented" + ) + }); + false + } + _ => false, + }, + StacksTransactionFilterPredicate::ContractCall(expected_contract_call) => { + match &transaction.metadata.kind { + StacksTransactionKind::ContractCall(actual_contract_call) => { + actual_contract_call + .contract_identifier + .eq(&expected_contract_call.contract_identifier) + && actual_contract_call + .method + .eq(&expected_contract_call.method) + } + _ => false, + } + } + StacksTransactionFilterPredicate::FtEvent(expected_event) => { + let expecting_mint = expected_event.actions.contains(&"mint".to_string()); + let expecting_transfer = expected_event.actions.contains(&"transfer".to_string()); + let expecting_burn = expected_event.actions.contains(&"burn".to_string()); + + for event in transaction.metadata.receipt.events.iter() { + match (event, expecting_mint, expecting_transfer, expecting_burn) { + (StacksTransactionEvent::FTMintEvent(_), true, _, _) => return true, + (StacksTransactionEvent::FTTransferEvent(_), _, true, _) => return true, + (StacksTransactionEvent::FTBurnEvent(_), _, _, true) => return true, + _ => continue, + } + } + false + } + StacksTransactionFilterPredicate::NftEvent(expected_event) => { + let expecting_mint = expected_event.actions.contains(&"mint".to_string()); + let expecting_transfer = expected_event.actions.contains(&"transfer".to_string()); + let expecting_burn = expected_event.actions.contains(&"burn".to_string()); + + for event in transaction.metadata.receipt.events.iter() { + match (event, expecting_mint, expecting_transfer, expecting_burn) { + (StacksTransactionEvent::NFTMintEvent(_), true, _, _) => return true, + (StacksTransactionEvent::NFTTransferEvent(_), _, true, _) => return true, + (StacksTransactionEvent::NFTBurnEvent(_), _, _, true) => return true, + _ => continue, + } + } + false + } + StacksTransactionFilterPredicate::StxEvent(expected_event) => { + let expecting_mint = expected_event.actions.contains(&"mint".to_string()); + let expecting_transfer = expected_event.actions.contains(&"transfer".to_string()); + let expecting_lock = expected_event.actions.contains(&"lock".to_string()); + + for event in transaction.metadata.receipt.events.iter() { + match (event, expecting_mint, expecting_transfer, expecting_lock) { + (StacksTransactionEvent::STXMintEvent(_), true, _, _) => return true, + (StacksTransactionEvent::STXTransferEvent(_), _, true, _) => return true, + (StacksTransactionEvent::STXLockEvent(_), _, _, true) => return true, + _ => continue, + } + } + false + } + StacksTransactionFilterPredicate::PrintEvent(expected_event) => { + for event in transaction.metadata.receipt.events.iter() { + match event { + StacksTransactionEvent::SmartContractEvent(actual) => { + if actual.contract_identifier == expected_event.contract_identifier { + let value = + format!("{}", expect_decoded_clarity_value(&actual.hex_value)); + if value.contains(&expected_event.contains) { + return true; + } + } + } + _ => {} + } + } + false + } + StacksTransactionFilterPredicate::TransactionIdentifierHash(txid) => { + txid.eq(&transaction.transaction_identifier.hash) + } + } +} + +fn encode_transaction_including_with_clarity_decoding( + transaction: &StacksTransactionData, + ctx: &Context, +) -> serde_json::Value { + json!({ + "transaction_identifier": transaction.transaction_identifier, + "operations": transaction.operations, + "metadata": { + "success": transaction.metadata.success, + "raw_tx": transaction.metadata.raw_tx, + "result": serialized_decoded_clarity_value(&transaction.metadata.result, ctx), + "sender": transaction.metadata.sender, + "fee": transaction.metadata.fee, + "kind": transaction.metadata.kind, + "receipt": { + "mutated_contracts_radius": transaction.metadata.receipt.mutated_contracts_radius, + "mutated_assets_radius": transaction.metadata.receipt.mutated_assets_radius, + "contract_calls_stack": transaction.metadata.receipt.contract_calls_stack, + "events": transaction.metadata.receipt.events.iter().map(|event| { + serialized_event_with_decoded_clarity_value(event, ctx) + }).collect::>(), + }, + "description": transaction.metadata.description, + "sponsor": transaction.metadata.sponsor, + "execution_cost": transaction.metadata.execution_cost, + "position": transaction.metadata.position, + }, + }) +} + +pub fn serialized_event_with_decoded_clarity_value( + event: &StacksTransactionEvent, + ctx: &Context, +) -> serde_json::Value { + match event { + StacksTransactionEvent::STXTransferEvent(payload) => { + json!({ + "type": "STXTransferEvent", + "data": payload + }) + } + StacksTransactionEvent::STXMintEvent(payload) => { + json!({ + "type": "STXMintEvent", + "data": payload + }) + } + StacksTransactionEvent::STXLockEvent(payload) => { + json!({ + "type": "STXLockEvent", + "data": payload + }) + } + StacksTransactionEvent::STXBurnEvent(payload) => { + json!({ + "type": "STXBurnEvent", + "data": payload + }) + } + StacksTransactionEvent::NFTTransferEvent(payload) => { + json!({ + "type": "NFTTransferEvent", + "data": { + "asset_class_identifier": payload.asset_class_identifier, + "asset_identifier": serialized_decoded_clarity_value(&payload.hex_asset_identifier, ctx), + "sender": payload.sender, + "recipient": payload.recipient, + } + }) + } + StacksTransactionEvent::NFTMintEvent(payload) => { + json!({ + "type": "NFTMintEvent", + "data": { + "asset_class_identifier": payload.asset_class_identifier, + "asset_identifier": serialized_decoded_clarity_value(&payload.hex_asset_identifier, ctx), + "recipient": payload.recipient, + } + }) + } + StacksTransactionEvent::NFTBurnEvent(payload) => { + json!({ + "type": "NFTBurnEvent", + "data": { + "asset_class_identifier": payload.asset_class_identifier, + "asset_identifier": serialized_decoded_clarity_value(&payload.hex_asset_identifier, ctx), + "sender": payload.sender, + } + }) + } + StacksTransactionEvent::FTTransferEvent(payload) => { + json!({ + "type": "FTTransferEvent", + "data": payload + }) + } + StacksTransactionEvent::FTMintEvent(payload) => { + json!({ + "type": "FTMintEvent", + "data": payload + }) + } + StacksTransactionEvent::FTBurnEvent(payload) => { + json!({ + "type": "FTBurnEvent", + "data": payload + }) + } + StacksTransactionEvent::DataVarSetEvent(payload) => { + json!({ + "type": "DataVarSetEvent", + "data": { + "contract_identifier": payload.contract_identifier, + "var": payload.var, + "new_value": serialized_decoded_clarity_value(&payload.hex_new_value, ctx), + } + }) + } + StacksTransactionEvent::DataMapInsertEvent(payload) => { + json!({ + "type": "DataMapInsertEvent", + "data": { + "contract_identifier": payload.contract_identifier, + "map": payload.map, + "inserted_key": serialized_decoded_clarity_value(&payload.hex_inserted_key, ctx), + "inserted_value": serialized_decoded_clarity_value(&payload.hex_inserted_value, ctx), + } + }) + } + StacksTransactionEvent::DataMapUpdateEvent(payload) => { + json!({ + "type": "DataMapUpdateEvent", + "data": { + "contract_identifier": payload.contract_identifier, + "map": payload.map, + "key": serialized_decoded_clarity_value(&payload.hex_key, ctx), + "new_value": serialized_decoded_clarity_value(&payload.hex_new_value, ctx), + } + }) + } + StacksTransactionEvent::DataMapDeleteEvent(payload) => { + json!({ + "type": "DataMapDeleteEvent", + "data": { + "contract_identifier": payload.contract_identifier, + "map": payload.map, + "deleted_key": serialized_decoded_clarity_value(&payload.hex_deleted_key, ctx), + } + }) + } + StacksTransactionEvent::SmartContractEvent(payload) => { + json!({ + "type": "SmartContractEvent", + "data": { + "contract_identifier": payload.contract_identifier, + "topic": payload.topic, + "value": serialized_decoded_clarity_value(&payload.hex_value, ctx), + } + }) + } + } +} + +pub fn expect_decoded_clarity_value(hex_value: &str) -> ClarityValue { + let hex_value = hex_value + .strip_prefix("0x") + .expect("unable to decode clarity value emitted by stacks-node"); + let value_bytes = + hex_bytes(&hex_value).expect("unable to decode clarity value emitted by stacks-node"); + ClarityValue::consensus_deserialize(&mut Cursor::new(&value_bytes)) + .expect("unable to decode clarity value emitted by stacks-node") +} + +pub fn serialized_decoded_clarity_value(hex_value: &str, ctx: &Context) -> serde_json::Value { + let hex_value = match hex_value.strip_prefix("0x") { + Some(hex_value) => hex_value, + _ => return json!(hex_value.to_string()), + }; + let value_bytes = match hex_bytes(&hex_value) { + Ok(bytes) => bytes, + _ => return json!(hex_value.to_string()), + }; + let value = match ClarityValue::consensus_deserialize(&mut Cursor::new(&value_bytes)) { + Ok(value) => serialize_to_json(&value), + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to deserialize clarity value {:?}", e) + }); + return json!(hex_value.to_string()); + } + }; + value +} + +pub fn serialize_to_json(value: &ClarityValue) -> serde_json::Value { + match value { + ClarityValue::Int(int) => json!(int), + ClarityValue::UInt(int) => json!(int), + ClarityValue::Bool(boolean) => json!(boolean), + ClarityValue::Principal(principal_data) => json!(format!("{}", principal_data)), + ClarityValue::Sequence(SequenceData::Buffer(vec_bytes)) => { + json!(format!("0x{}", &vec_bytes)) + } + ClarityValue::Sequence(SequenceData::String(CharType::ASCII(string))) => { + json!(String::from_utf8(string.data.clone()).unwrap()) + } + ClarityValue::Sequence(SequenceData::String(CharType::UTF8(string))) => { + let mut result = String::new(); + for c in string.data.iter() { + if c.len() > 1 { + result.push_str(&String::from_utf8(c.to_vec()).unwrap()); + } else { + result.push(c[0] as char) + } + } + json!(result) + } + ClarityValue::Optional(opt_data) => match &opt_data.data { + None => serde_json::Value::Null, + Some(value) => serialize_to_json(&*value), + }, + ClarityValue::Response(res_data) => { + json!({ + "result": { + "success": res_data.committed, + "value": serialize_to_json(&*res_data.data), + } + }) + } + ClarityValue::Tuple(data) => { + let mut map = serde_json::Map::new(); + for (name, value) in data.data_map.iter() { + map.insert(name.to_string(), serialize_to_json(value)); + } + json!(map) + } + ClarityValue::Sequence(SequenceData::List(list_data)) => { + let mut list = vec![]; + for value in list_data.data.iter() { + list.push(serialize_to_json(value)); + } + json!(list) + } + ClarityValue::CallableContract(callable) => { + json!(format!("{}", callable.contract_identifier)) + } + } +} + +pub fn serialize_stacks_payload_to_json<'a>( + trigger: StacksTriggerChainhook<'a>, + _proofs: &HashMap<&'a TransactionIdentifier, String>, + ctx: &Context, +) -> JsonValue { + let decode_clarity_values = trigger.should_decode_clarity_value(); + json!({ + "apply": trigger.apply.into_iter().map(|(transactions, block)| { + json!({ + "block_identifier": block.get_identifier(), + "parent_block_identifier": block.get_parent_identifier(), + "timestamp": block.get_timestamp(), + "transactions": transactions.iter().map(|transaction| { + if decode_clarity_values { + encode_transaction_including_with_clarity_decoding(transaction, ctx) + } else { + json!(transaction) + } + }).collect::>(), + "metadata": block.get_serialized_metadata(), + }) + }).collect::>(), + "rollback": trigger.rollback.into_iter().map(|(transactions, block)| { + json!({ + "block_identifier": block.get_identifier(), + "parent_block_identifier": block.get_parent_identifier(), + "timestamp": block.get_timestamp(), + "transactions": transactions.iter().map(|transaction| { + if decode_clarity_values { + encode_transaction_including_with_clarity_decoding(transaction, ctx) + } else { + json!(transaction) + } + }).collect::>(), + "metadata": block.get_serialized_metadata(), + // "proof": proofs.get(&transaction.transaction_identifier), + }) + }).collect::>(), + "chainhook": { + "uuid": trigger.chainhook.uuid, + "transaction_predicate": trigger.chainhook.transaction_predicate, + "block_predicate": trigger.chainhook.transaction_predicate, + } + }) +} + +pub fn handle_stacks_hook_action<'a>( + trigger: StacksTriggerChainhook<'a>, + proofs: &HashMap<&'a TransactionIdentifier, String>, + ctx: &Context, +) -> Option { + match &trigger.chainhook.action { + HookAction::Http(http) => { + let client = Client::builder().build().unwrap(); + let host = format!("{}", http.url); + let method = Method::from_bytes(http.method.as_bytes()).unwrap(); + let body = serde_json::to_vec(&serialize_stacks_payload_to_json(trigger, proofs, ctx)) + .unwrap(); + Some(StacksChainhookOccurrence::Http( + client + .request(method, &host) + .header("Content-Type", "application/json") + .body(body), + )) + } + HookAction::File(disk) => { + let bytes = serde_json::to_vec(&serialize_stacks_payload_to_json(trigger, proofs, ctx)) + .unwrap(); + Some(StacksChainhookOccurrence::File( + disk.path.to_string(), + bytes, + )) + } + HookAction::Noop => Some(StacksChainhookOccurrence::Data( + StacksChainhookOccurrencePayload { + apply: trigger + .apply + .into_iter() + .map(|(transactions, block)| { + let transactions = transactions + .into_iter() + .map(|t| t.clone()) + .collect::>(); + StacksApplyTransactionPayload { + block_identifier: block.get_identifier().clone(), + transactions, + } + }) + .collect::>(), + rollback: trigger + .rollback + .into_iter() + .map(|(transactions, block)| { + let transactions = transactions + .into_iter() + .map(|t| t.clone()) + .collect::>(); + StacksRollbackTransactionPayload { + block_identifier: block.get_identifier().clone(), + transactions, + } + }) + .collect::>(), + chainhook: StacksChainhookPayload { + uuid: trigger.chainhook.uuid.clone(), + }, + }, + )), + } +} diff --git a/components/chainhook-event-observer/src/chainhooks/types.rs b/components/chainhook-event-observer/src/chainhooks/types.rs new file mode 100644 index 0000000..3fe066d --- /dev/null +++ b/components/chainhook-event-observer/src/chainhooks/types.rs @@ -0,0 +1,1064 @@ +use clarity_repl::clarity::util::hash::hex_bytes; +use reqwest::Url; +use serde::ser::{SerializeSeq, Serializer}; +use serde::{Deserialize, Serialize}; + +use chainhook_types::{BitcoinNetwork, StacksNetwork}; + +use schemars::JsonSchema; + +use crate::observer::ApiKey; + +#[derive(Clone, Debug, JsonSchema)] +pub struct ChainhookConfig { + pub stacks_chainhooks: Vec, + pub bitcoin_chainhooks: Vec, +} + +impl ChainhookConfig { + pub fn new() -> ChainhookConfig { + ChainhookConfig { + stacks_chainhooks: vec![], + bitcoin_chainhooks: vec![], + } + } + + pub fn get_serialized_stacks_predicates( + &self, + ) -> Vec<(&String, &StacksNetwork, &StacksTransactionFilterPredicate)> { + let mut stacks = vec![]; + for chainhook in self.stacks_chainhooks.iter() { + stacks.push(( + &chainhook.uuid, + &chainhook.network, + &chainhook.transaction_predicate, + )); + } + stacks + } + + pub fn get_serialized_bitcoin_predicates( + &self, + ) -> Vec<(&String, &BitcoinNetwork, &BitcoinTransactionFilterPredicate)> { + let mut bitcoin = vec![]; + for chainhook in self.bitcoin_chainhooks.iter() { + bitcoin.push((&chainhook.uuid, &chainhook.network, &chainhook.predicate)); + } + bitcoin + } + + pub fn register_hook(&mut self, hook: ChainhookSpecification) { + match hook { + ChainhookSpecification::Stacks(hook) => self.stacks_chainhooks.push(hook), + ChainhookSpecification::Bitcoin(hook) => self.bitcoin_chainhooks.push(hook), + }; + } + + pub fn deregister_stacks_hook( + &mut self, + hook_uuid: String, + ) -> Option { + let mut i = 0; + while i < self.stacks_chainhooks.len() { + if self.stacks_chainhooks[i].uuid == hook_uuid { + let hook = self.stacks_chainhooks.remove(i); + return Some(hook); + } else { + i += 1; + } + } + None + } + + pub fn deregister_bitcoin_hook( + &mut self, + hook_uuid: String, + ) -> Option { + let mut i = 0; + while i < self.bitcoin_chainhooks.len() { + if self.bitcoin_chainhooks[i].uuid == hook_uuid { + let hook = self.bitcoin_chainhooks.remove(i); + return Some(hook); + } else { + i += 1; + } + } + None + } +} + +impl Serialize for ChainhookConfig { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(Some( + self.bitcoin_chainhooks.len() + self.stacks_chainhooks.len(), + ))?; + for chainhook in self.bitcoin_chainhooks.iter() { + seq.serialize_element(chainhook)?; + } + for chainhook in self.stacks_chainhooks.iter() { + seq.serialize_element(chainhook)?; + } + seq.end() + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ChainhookSpecification { + Bitcoin(BitcoinChainhookSpecification), + Stacks(StacksChainhookSpecification), +} + +impl ChainhookSpecification { + pub fn name(&self) -> &str { + match &self { + Self::Bitcoin(data) => &data.name, + Self::Stacks(data) => &data.name, + } + } + + pub fn set_owner_uuid(&mut self, api_key: &ApiKey) { + match self { + Self::Bitcoin(ref mut data) => { + data.owner_uuid = api_key.0.clone(); + } + Self::Stacks(ref mut data) => { + data.owner_uuid = api_key.0.clone(); + } + } + } + + pub fn key(&self) -> String { + match &self { + Self::Bitcoin(data) => format!( + "chainhook:btc:{}:{}", + data.owner_uuid.as_deref().unwrap_or("0".into()), + data.uuid + ), + Self::Stacks(data) => format!( + "chainhook:stx:{}:{}", + data.owner_uuid.as_deref().unwrap_or("0".into()), + data.uuid + ), + } + } + + pub fn deserialize_specification( + spec: &str, + _key: &str, + ) -> Result { + let spec: ChainhookSpecification = serde_json::from_str(spec) + .map_err(|e| format!("unable to deserialize Stacks chainhook {}", e.to_string()))?; + Ok(spec) + } + + pub fn uuid(&self) -> &str { + match &self { + Self::Bitcoin(data) => &data.uuid, + Self::Stacks(data) => &data.uuid, + } + } + + pub fn validate(&self) -> Result<(), String> { + match &self { + Self::Bitcoin(data) => { + let _ = data.action.validate()?; + } + Self::Stacks(data) => { + let _ = data.action.validate()?; + } + } + Ok(()) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +pub struct BitcoinChainhookSpecification { + pub uuid: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub owner_uuid: Option, + pub name: String, + pub network: BitcoinNetwork, + pub version: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_block: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub end_block: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub expire_after_occurrence: Option, + pub predicate: BitcoinTransactionFilterPredicate, + pub action: HookAction, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum HookAction { + Http(HttpHook), + File(FileHook), + Noop, +} + +impl HookAction { + pub fn validate(&self) -> Result<(), String> { + match &self { + HookAction::Http(spec) => { + let _ = Url::parse(&spec.url) + .map_err(|e| format!("hook action url invalid ({})", e.to_string()))?; + } + HookAction::File(_) => {} + HookAction::Noop => {} + } + Ok(()) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct HttpHook { + pub url: String, + pub method: String, + pub authorization_header: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct FileHook { + pub path: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +pub struct ScriptTemplate { + pub instructions: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ScriptInstruction { + Opcode(u8), + RawBytes(Vec), + Placeholder(String, u8), +} + +impl ScriptTemplate { + pub fn parse(template: &str) -> Result { + let raw_instructions = template + .split_ascii_whitespace() + .map(|c| c.to_string()) + .collect::>(); + let mut instructions = vec![]; + for raw_instruction in raw_instructions.into_iter() { + if raw_instruction.starts_with("{") { + let placeholder = &raw_instruction[1..raw_instruction.len() - 1]; + let (name, size) = match placeholder.split_once(":") { + Some(res) => res, + None => return Err(format!("malformed placeholder {}: should be {{placeholder-name:number-of-bytes}} (ex: {{id:4}}", raw_instruction)) + }; + let size = match size.parse::() { + Ok(res) => res, + Err(_) => return Err(format!("malformed placeholder {}: should be {{placeholder-name:number-of-bytes}} (ex: {{id:4}}", raw_instruction)) + }; + instructions.push(ScriptInstruction::Placeholder(name.to_string(), size)); + } else if let Some(opcode) = opcode_to_hex(&raw_instruction) { + instructions.push(ScriptInstruction::Opcode(opcode)); + } else if let Ok(bytes) = hex_bytes(&raw_instruction) { + instructions.push(ScriptInstruction::RawBytes(bytes)); + } else { + return Err(format!("unable to handle instruction {}", raw_instruction)); + } + } + Ok(ScriptTemplate { instructions }) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct BitcoinTransactionFilterPredicate { + pub scope: Scope, + #[serde(flatten)] + pub kind: BitcoinPredicateType, +} + +impl BitcoinTransactionFilterPredicate { + pub fn new(scope: Scope, kind: BitcoinPredicateType) -> BitcoinTransactionFilterPredicate { + BitcoinTransactionFilterPredicate { scope, kind } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +#[serde(tag = "type", content = "rule")] +pub enum BitcoinPredicateType { + TransactionIdentifierHash(ExactMatchingRule), + OpReturn(MatchingRule), + P2pkh(ExactMatchingRule), + P2sh(ExactMatchingRule), + P2wpkh(ExactMatchingRule), + P2wsh(ExactMatchingRule), + Pox(PoxPredicate), + Pob(PobPredicate), + KeyRegistration(KeyRegistrationPredicate), + TransferSTX(TransferSTXPredicate), + LockSTX(LockSTXPredicate), +} + +pub fn get_canonical_magic_bytes(network: &BitcoinNetwork) -> [u8; 2] { + match network { + BitcoinNetwork::Mainnet => ['X' as u8, '2' as u8], + BitcoinNetwork::Testnet => ['T' as u8, '2' as u8], + BitcoinNetwork::Regtest => ['i' as u8, 'd' as u8], + } +} + +pub struct PoxConfig { + pub genesis_block_height: u64, + pub prepare_phase_len: u64, + pub reward_phase_len: u64, + pub rewarded_addresses_per_block: usize, +} + +impl PoxConfig { + pub fn is_consensus_rewarding_participants_at_block_height(&self, block_height: u64) -> bool { + (block_height.saturating_div(self.genesis_block_height) % self.get_pox_cycle_len()) + >= self.prepare_phase_len + } + + pub fn get_pox_cycle_len(&self) -> u64 { + self.prepare_phase_len + self.reward_phase_len + } +} + +const POX_CONFIG_MAINNET: PoxConfig = PoxConfig { + genesis_block_height: 666050, + prepare_phase_len: 2100, + reward_phase_len: 100, + rewarded_addresses_per_block: 2, +}; + +const POX_CONFIG_TESTNET: PoxConfig = PoxConfig { + genesis_block_height: 2000000, + prepare_phase_len: 1050, + reward_phase_len: 50, + rewarded_addresses_per_block: 2, +}; + +const POX_CONFIG_DEVNET: PoxConfig = PoxConfig { + genesis_block_height: 100, + prepare_phase_len: 10, + reward_phase_len: 4, + rewarded_addresses_per_block: 2, +}; + +pub fn get_canonical_pox_config(network: &BitcoinNetwork) -> PoxConfig { + match network { + BitcoinNetwork::Mainnet => POX_CONFIG_MAINNET, + BitcoinNetwork::Testnet => POX_CONFIG_TESTNET, + BitcoinNetwork::Regtest => POX_CONFIG_DEVNET, + } +} + +#[derive(Debug, Clone, PartialEq)] +#[repr(u8)] +pub enum StacksOpcodes { + BlockCommit = '[' as u8, + KeyRegister = '^' as u8, + StackStx = 'x' as u8, + PreStx = 'p' as u8, + TransferStx = '$' as u8, +} + +impl TryFrom for StacksOpcodes { + type Error = (); + + fn try_from(v: u8) -> Result { + match v { + x if x == StacksOpcodes::BlockCommit as u8 => Ok(StacksOpcodes::BlockCommit), + x if x == StacksOpcodes::KeyRegister as u8 => Ok(StacksOpcodes::KeyRegister), + x if x == StacksOpcodes::StackStx as u8 => Ok(StacksOpcodes::StackStx), + x if x == StacksOpcodes::PreStx as u8 => Ok(StacksOpcodes::PreStx), + x if x == StacksOpcodes::TransferStx as u8 => Ok(StacksOpcodes::TransferStx), + _ => Err(()), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum KeyRegistrationPredicate { + Any, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum TransferSTXPredicate { + Any, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum LockSTXPredicate { + Any, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PoxPredicate { + Any, + Recipient(MatchingRule), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PobPredicate { + Any, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BlockIdentifierIndexRule { + Equals(u64), + HigherThan(u64), + LowerThan(u64), + Between(u64, u64), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum Scope { + Inputs, + Outputs, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum MatchingRule { + Equals(String), + StartsWith(String), + EndsWith(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExactMatchingRule { + Equals(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BlockIdentifierHashRule { + Equals(String), + BuildsOff(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +pub struct StacksChainhookSpecification { + pub uuid: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub owner_uuid: Option, + pub name: String, + pub network: StacksNetwork, + pub version: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_block: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub end_block: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub expire_after_occurrence: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub capture_all_events: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub decode_clarity_values: Option, + #[serde(rename = "predicate")] + pub transaction_predicate: StacksTransactionFilterPredicate, + pub block_predicate: Option, + pub action: HookAction, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +#[serde(tag = "type", content = "rule")] +pub enum StacksBlockFilterPredicate { + BlockIdentifierHash(BlockIdentifierHashRule), + BlockIdentifierIndex(BlockIdentifierIndexRule), + BitcoinBlockIdentifierHash(BlockIdentifierHashRule), + BitcoinBlockIdentifierIndex(BlockIdentifierHashRule), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +#[serde(tag = "type", content = "rule")] +pub enum StacksTransactionFilterPredicate { + ContractDeployment(StacksContractDeploymentPredicate), + ContractCall(StacksContractCallBasedPredicate), + PrintEvent(StacksPrintEventBasedPredicate), + FtEvent(StacksFtEventBasedPredicate), + NftEvent(StacksNftEventBasedPredicate), + StxEvent(StacksStxEventBasedPredicate), + TransactionIdentifierHash(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct StacksContractCallBasedPredicate { + pub contract_identifier: String, + pub method: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +#[serde(tag = "type", content = "rule")] +pub enum StacksContractDeploymentPredicate { + Principal(String), + Trait(String), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct StacksPrintEventBasedPredicate { + pub contract_identifier: String, + pub contains: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct StacksFtEventBasedPredicate { + pub asset_identifier: String, + pub actions: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct StacksNftEventBasedPredicate { + pub asset_identifier: String, + pub actions: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub struct StacksStxEventBasedPredicate { + pub actions: Vec, +} + +pub fn opcode_to_hex(asm: &str) -> Option { + match asm { + "OP_PUSHBYTES_0" => Some(0x00), + // Push the next byte as an array onto the stack + "OP_PUSHBYTES_1" => Some(0x01), + // Push the next 2 bytes as an array onto the stack + "OP_PUSHBYTES_2" => Some(0x02), + // Push the next 2 bytes as an array onto the stack + "OP_PUSHBYTES_3" => Some(0x03), + // Push the next 4 bytes as an array onto the stack + "OP_PUSHBYTES_4" => Some(0x04), + // Push the next 5 bytes as an array onto the stack + "OP_PUSHBYTES_5" => Some(0x05), + // Push the next 6 bytes as an array onto the stack + "OP_PUSHBYTES_6" => Some(0x06), + // Push the next 7 bytes as an array onto the stack + "OP_PUSHBYTES_7" => Some(0x07), + // Push the next 8 bytes as an array onto the stack + "OP_PUSHBYTES_8" => Some(0x08), + // Push the next 9 bytes as an array onto the stack + "OP_PUSHBYTES_9" => Some(0x09), + // Push the next 10 bytes as an array onto the stack + "OP_PUSHBYTES_10" => Some(0x0a), + // Push the next 11 bytes as an array onto the stack + "OP_PUSHBYTES_11" => Some(0x0b), + // Push the next 12 bytes as an array onto the stack + "OP_PUSHBYTES_12" => Some(0x0c), + // Push the next 13 bytes as an array onto the stack + "OP_PUSHBYTES_13" => Some(0x0d), + // Push the next 14 bytes as an array onto the stack + "OP_PUSHBYTES_14" => Some(0x0e), + // Push the next 15 bytes as an array onto the stack + "OP_PUSHBYTES_15" => Some(0x0f), + // Push the next 16 bytes as an array onto the stack + "OP_PUSHBYTES_16" => Some(0x10), + // Push the next 17 bytes as an array onto the stack + "OP_PUSHBYTES_17" => Some(0x11), + // Push the next 18 bytes as an array onto the stack + "OP_PUSHBYTES_18" => Some(0x12), + // Push the next 19 bytes as an array onto the stack + "OP_PUSHBYTES_19" => Some(0x13), + // Push the next 20 bytes as an array onto the stack + "OP_PUSHBYTES_20" => Some(0x14), + // Push the next 21 bytes as an array onto the stack + "OP_PUSHBYTES_21" => Some(0x15), + // Push the next 22 bytes as an array onto the stack + "OP_PUSHBYTES_22" => Some(0x16), + // Push the next 23 bytes as an array onto the stack + "OP_PUSHBYTES_23" => Some(0x17), + // Push the next 24 bytes as an array onto the stack + "OP_PUSHBYTES_24" => Some(0x18), + // Push the next 25 bytes as an array onto the stack + "OP_PUSHBYTES_25" => Some(0x19), + // Push the next 26 bytes as an array onto the stack + "OP_PUSHBYTES_26" => Some(0x1a), + // Push the next 27 bytes as an array onto the stack + "OP_PUSHBYTES_27" => Some(0x1b), + // Push the next 28 bytes as an array onto the stack + "OP_PUSHBYTES_28" => Some(0x1c), + // Push the next 29 bytes as an array onto the stack + "OP_PUSHBYTES_29" => Some(0x1d), + // Push the next 30 bytes as an array onto the stack + "OP_PUSHBYTES_30" => Some(0x1e), + // Push the next 31 bytes as an array onto the stack + "OP_PUSHBYTES_31" => Some(0x1f), + // Push the next 32 bytes as an array onto the stack + "OP_PUSHBYTES_32" => Some(0x20), + // Push the next 33 bytes as an array onto the stack + "OP_PUSHBYTES_33" => Some(0x21), + // Push the next 34 bytes as an array onto the stack + "OP_PUSHBYTES_34" => Some(0x22), + // Push the next 35 bytes as an array onto the stack + "OP_PUSHBYTES_35" => Some(0x23), + // Push the next 36 bytes as an array onto the stack + "OP_PUSHBYTES_36" => Some(0x24), + // Push the next 37 bytes as an array onto the stack + "OP_PUSHBYTES_37" => Some(0x25), + // Push the next 38 bytes as an array onto the stack + "OP_PUSHBYTES_38" => Some(0x26), + // Push the next 39 bytes as an array onto the stack + "OP_PUSHBYTES_39" => Some(0x27), + // Push the next 40 bytes as an array onto the stack + "OP_PUSHBYTES_40" => Some(0x28), + // Push the next 41 bytes as an array onto the stack + "OP_PUSHBYTES_41" => Some(0x29), + // Push the next 42 bytes as an array onto the stack + "OP_PUSHBYTES_42" => Some(0x2a), + // Push the next 43 bytes as an array onto the stack + "OP_PUSHBYTES_43" => Some(0x2b), + // Push the next 44 bytes as an array onto the stack + "OP_PUSHBYTES_44" => Some(0x2c), + // Push the next 45 bytes as an array onto the stack + "OP_PUSHBYTES_45" => Some(0x2d), + // Push the next 46 bytes as an array onto the stack + "OP_PUSHBYTES_46" => Some(0x2e), + // Push the next 47 bytes as an array onto the stack + "OP_PUSHBYTES_47" => Some(0x2f), + // Push the next 48 bytes as an array onto the stack + "OP_PUSHBYTES_48" => Some(0x30), + // Push the next 49 bytes as an array onto the stack + "OP_PUSHBYTES_49" => Some(0x31), + // Push the next 50 bytes as an array onto the stack + "OP_PUSHBYTES_50" => Some(0x32), + // Push the next 51 bytes as an array onto the stack + "OP_PUSHBYTES_51" => Some(0x33), + // Push the next 52 bytes as an array onto the stack + "OP_PUSHBYTES_52" => Some(0x34), + // Push the next 53 bytes as an array onto the stack + "OP_PUSHBYTES_53" => Some(0x35), + // Push the next 54 bytes as an array onto the stack + "OP_PUSHBYTES_54" => Some(0x36), + // Push the next 55 bytes as an array onto the stack + "OP_PUSHBYTES_55" => Some(0x37), + // Push the next 56 bytes as an array onto the stack + "OP_PUSHBYTES_56" => Some(0x38), + // Push the next 57 bytes as an array onto the stack + "OP_PUSHBYTES_57" => Some(0x39), + // Push the next 58 bytes as an array onto the stack + "OP_PUSHBYTES_58" => Some(0x3a), + // Push the next 59 bytes as an array onto the stack + "OP_PUSHBYTES_59" => Some(0x3b), + // Push the next 60 bytes as an array onto the stack + "OP_PUSHBYTES_60" => Some(0x3c), + // Push the next 61 bytes as an array onto the stack + "OP_PUSHBYTES_61" => Some(0x3d), + // Push the next 62 bytes as an array onto the stack + "OP_PUSHBYTES_62" => Some(0x3e), + // Push the next 63 bytes as an array onto the stack + "OP_PUSHBYTES_63" => Some(0x3f), + // Push the next 64 bytes as an array onto the stack + "OP_PUSHBYTES_64" => Some(0x40), + // Push the next 65 bytes as an array onto the stack + "OP_PUSHBYTES_65" => Some(0x41), + // Push the next 66 bytes as an array onto the stack + "OP_PUSHBYTES_66" => Some(0x42), + // Push the next 67 bytes as an array onto the stack + "OP_PUSHBYTES_67" => Some(0x43), + // Push the next 68 bytes as an array onto the stack + "OP_PUSHBYTES_68" => Some(0x44), + // Push the next 69 bytes as an array onto the stack + "OP_PUSHBYTES_69" => Some(0x45), + // Push the next 70 bytes as an array onto the stack + "OP_PUSHBYTES_70" => Some(0x46), + // Push the next 71 bytes as an array onto the stack + "OP_PUSHBYTES_71" => Some(0x47), + // Push the next 72 bytes as an array onto the stack + "OP_PUSHBYTES_72" => Some(0x48), + // Push the next 73 bytes as an array onto the stack + "OP_PUSHBYTES_73" => Some(0x49), + // Push the next 74 bytes as an array onto the stack + "OP_PUSHBYTES_74" => Some(0x4a), + // Push the next 75 bytes as an array onto the stack + "OP_PUSHBYTES_75" => Some(0x4b), + // Read the next byte as N; push the next N bytes as an array onto the stack + "OP_PUSHDATA1" => Some(0x4c), + // Read the next 2 bytes as N; push the next N bytes as an array onto the stack + "OP_PUSHDATA2" => Some(0x4d), + // Read the next 4 bytes as N; push the next N bytes as an array onto the stack + "OP_PUSHDATA4" => Some(0x4e), + // Push the array `0x81` onto the stack + "OP_PUSHNUM_NEG1" => Some(0x4f), + // Synonym for OP_RETURN + "OP_RESERVED" => Some(0x50), + // Push the number `0x01` onto the stack + "OP_PUSHNUM_1" => Some(0x51), + // Push the number `0x02` onto the stack + "OP_PUSHNUM_2" => Some(0x52), + // Push the number `0x03` onto the stack + "OP_PUSHNUM_3" => Some(0x53), + // Push the number `0x04` onto the stack + "OP_PUSHNUM_4" => Some(0x54), + // Push the number `0x05` onto the stack + "OP_PUSHNUM_5" => Some(0x55), + // Push the number `0x06` onto the stack + "OP_PUSHNUM_6" => Some(0x56), + // Push the number `0x07` onto the stack + "OP_PUSHNUM_7" => Some(0x57), + // Push the number `0x08` onto the stack + "OP_PUSHNUM_8" => Some(0x58), + // Push the number `0x09` onto the stack + "OP_PUSHNUM_9" => Some(0x59), + // Push the number `0x0a` onto the stack + "OP_PUSHNUM_10" => Some(0x5a), + // Push the number `0x0b` onto the stack + "OP_PUSHNUM_11" => Some(0x5b), + // Push the number `0x0c` onto the stack + "OP_PUSHNUM_12" => Some(0x5c), + // Push the number `0x0d` onto the stack + "OP_PUSHNUM_13" => Some(0x5d), + // Push the number `0x0e` onto the stack + "OP_PUSHNUM_14" => Some(0x5e), + // Push the number `0x0f` onto the stack + "OP_PUSHNUM_15" => Some(0x5f), + // Push the number `0x10` onto the stack + "OP_PUSHNUM_16" => Some(0x60), + // Does nothing + "OP_NOP" => Some(0x61), + // Synonym for OP_RETURN + "OP_VER" => Some(0x62), + // Pop and execute the next statements if a nonzero element was popped + "OP_IF" => Some(0x63), + // Pop and execute the next statements if a zero element was popped + "OP_NOTIF" => Some(0x64), + // Fail the script unconditionally, does not even need to be executed + "OP_VERIF" => Some(0x65), + // Fail the script unconditionally, does not even need to be executed + "OP_VERNOTIF" => Some(0x66), + // Execute statements if those after the previous OP_IF were not, and vice-versa. + // If there is no previous OP_IF, this acts as a RETURN. + "OP_ELSE" => Some(0x67), + // Pop and execute the next statements if a zero element was popped + "OP_ENDIF" => Some(0x68), + // If the top value is zero or the stack is empty, fail; otherwise, pop the stack + "OP_VERIFY" => Some(0x69), + // Fail the script immediately. (Must be executed.) + "OP_RETURN" => Some(0x6a), + // Pop one element from the main stack onto the alt stack + "OP_TOALTSTACK" => Some(0x6b), + // Pop one element from the alt stack onto the main stack + "OP_FROMALTSTACK" => Some(0x6c), + // Drops the top two stack items + "OP_2DROP" => Some(0x6d), + // Duplicates the top two stack items as AB -> ABAB + "OP_2DUP" => Some(0x6e), + // Duplicates the two three stack items as ABC -> ABCABC + "OP_3DUP" => Some(0x6f), + // Copies the two stack items of items two spaces back to + // the front, as xxAB -> ABxxAB + "OP_2OVER" => Some(0x70), + // Moves the two stack items four spaces back to the front, + // as xxxxAB -> ABxxxx + "OP_2ROT" => Some(0x71), + // Swaps the top two pairs, as ABCD -> CDAB + "OP_2SWAP" => Some(0x72), + // Duplicate the top stack element unless it is zero + "OP_IFDUP" => Some(0x73), + // Push the current number of stack items onto the stack + "OP_DEPTH" => Some(0x74), + // Drops the top stack item + "OP_DROP" => Some(0x75), + // Duplicates the top stack item + "OP_DUP" => Some(0x76), + // Drops the second-to-top stack item + "OP_NIP" => Some(0x77), + // Copies the second-to-top stack item, as xA -> AxA + "OP_OVER" => Some(0x78), + // Pop the top stack element as N. Copy the Nth stack element to the top + "OP_PICK" => Some(0x79), + // Pop the top stack element as N. Move the Nth stack element to the top + "OP_ROLL" => Some(0x7a), + // Rotate the top three stack items, as [top next1 next2] -> [next2 top next1] + "OP_ROT" => Some(0x7b), + // Swap the top two stack items + "OP_SWAP" => Some(0x7c), + // Copy the top stack item to before the second item, as [top next] -> [top next top] + "OP_TUCK" => Some(0x7d), + // Fail the script unconditionally, does not even need to be executed + "OP_CAT" => Some(0x7e), + // Fail the script unconditionally, does not even need to be executed + "OP_SUBSTR" => Some(0x7f), + // Fail the script unconditionally, does not even need to be executed + "OP_LEFT" => Some(0x80), + // Fail the script unconditionally, does not even need to be executed + "OP_RIGHT" => Some(0x81), + // Pushes the length of the top stack item onto the stack + "OP_SIZE" => Some(0x82), + // Fail the script unconditionally, does not even need to be executed + "OP_INVERT" => Some(0x83), + // Fail the script unconditionally, does not even need to be executed + "OP_AND" => Some(0x84), + // Fail the script unconditionally, does not even need to be executed + "OP_OR" => Some(0x85), + // Fail the script unconditionally, does not even need to be executed + "OP_XOR" => Some(0x86), + // Pushes 1 if the inputs are exactly equal, 0 otherwise + "OP_EQUAL" => Some(0x87), + // Returns success if the inputs are exactly equal, failure otherwise + "OP_EQUALVERIFY" => Some(0x88), + // Synonym for OP_RETURN + "OP_RESERVED1" => Some(0x89), + // Synonym for OP_RETURN + "OP_RESERVED2" => Some(0x8a), + // Increment the top stack element in place + "OP_1ADD" => Some(0x8b), + // Decrement the top stack element in place + "OP_1SUB" => Some(0x8c), + // Fail the script unconditionally, does not even need to be executed + "OP_2MUL" => Some(0x8d), + // Fail the script unconditionally, does not even need to be executed + "OP_2DIV" => Some(0x8e), + // Multiply the top stack item by -1 in place + "OP_NEGATE" => Some(0x8f), + // Absolute value the top stack item in place + "OP_ABS" => Some(0x90), + // Map 0 to 1 and everything else to 0, in place + "OP_NOT" => Some(0x91), + // Map 0 to 0 and everything else to 1, in place + "OP_0NOTEQUAL" => Some(0x92), + // Pop two stack items and push their sum + "OP_ADD" => Some(0x93), + // Pop two stack items and push the second minus the top + "OP_SUB" => Some(0x94), + // Fail the script unconditionally, does not even need to be executed + "OP_MUL" => Some(0x95), + // Fail the script unconditionally, does not even need to be executed + "OP_DIV" => Some(0x96), + // Fail the script unconditionally, does not even need to be executed + "OP_MOD" => Some(0x97), + // Fail the script unconditionally, does not even need to be executed + "OP_LSHIFT" => Some(0x98), + // Fail the script unconditionally, does not even need to be executed + "OP_RSHIFT" => Some(0x99), + // Pop the top two stack items and push 1 if both are nonzero, else push 0 + "OP_BOOLAND" => Some(0x9a), + // Pop the top two stack items and push 1 if either is nonzero, else push 0 + "OP_BOOLOR" => Some(0x9b), + // Pop the top two stack items and push 1 if both are numerically equal, else push 0 + "OP_NUMEQUAL" => Some(0x9c), + // Pop the top two stack items and return success if both are numerically equal, else return failure + "OP_NUMEQUALVERIFY" => Some(0x9d), + // Pop the top two stack items and push 0 if both are numerically equal, else push 1 + "OP_NUMNOTEQUAL" => Some(0x9e), + // Pop the top two items; push 1 if the second is less than the top, 0 otherwise + "OP_LESSTHAN" => Some(0x9f), + // Pop the top two items; push 1 if the second is greater than the top, 0 otherwise + "OP_GREATERTHAN" => Some(0xa0), + // Pop the top two items; push 1 if the second is <= the top, 0 otherwise + "OP_LESSTHANOREQUAL" => Some(0xa1), + // Pop the top two items; push 1 if the second is >= the top, 0 otherwise + "OP_GREATERTHANOREQUAL" => Some(0xa2), + // Pop the top two items; push the smaller + "OP_MIN" => Some(0xa3), + // Pop the top two items; push the larger + "OP_MAX" => Some(0xa4), + // Pop the top three items; if the top is >= the second and < the third, push 1, otherwise push 0 + "OP_WITHIN" => Some(0xa5), + // Pop the top stack item and push its RIPEMD160 hash + "OP_RIPEMD160" => Some(0xa6), + // Pop the top stack item and push its SHA1 hash + "OP_SHA1" => Some(0xa7), + // Pop the top stack item and push its SHA256 hash + "OP_SHA256" => Some(0xa8), + // Pop the top stack item and push its RIPEMD(SHA256) hash + "OP_HASH160" => Some(0xa9), + // Pop the top stack item and push its SHA256(SHA256) hash + "OP_HASH256" => Some(0xaa), + // Ignore this and everything preceding when deciding what to sign when signature-checking + "OP_CODESEPARATOR" => Some(0xab), + // pushing 1/0 for success/failure + "OP_CHECKSIG" => Some(0xac), + // returning success/failure + "OP_CHECKSIGVERIFY" => Some(0xad), + // Pop N, N pubkeys, M, M signatures, a dummy (due to bug in reference code), and verify that all M signatures are valid. + // Push 1 for "all valid", 0 otherwise + "OP_CHECKMULTISIG" => Some(0xae), + // Like the above but return success/failure + "OP_CHECKMULTISIGVERIFY" => Some(0xaf), + // Does nothing + "OP_NOP1" => Some(0xb0), + // + "OP_CLTV" => Some(0xb1), + // + "OP_CSV" => Some(0xb2), + // Does nothing + "OP_NOP4" => Some(0xb3), + // Does nothing + "OP_NOP5" => Some(0xb4), + // Does nothing + "OP_NOP6" => Some(0xb5), + // Does nothing + "OP_NOP7" => Some(0xb6), + // Does nothing + "OP_NOP8" => Some(0xb7), + // Does nothing + "OP_NOP9" => Some(0xb8), + // Does nothing + "OP_NOP10" => Some(0xb9), + // Every other opcode acts as OP_RETURN + // Synonym for OP_RETURN + "OP_RETURN_186" => Some(0xba), + // Synonym for OP_RETURN + "OP_RETURN_187" => Some(0xbb), + // Synonym for OP_RETURN + "OP_RETURN_188" => Some(0xbc), + // Synonym for OP_RETURN + "OP_RETURN_189" => Some(0xbd), + // Synonym for OP_RETURN + "OP_RETURN_190" => Some(0xbe), + // Synonym for OP_RETURN + "OP_RETURN_191" => Some(0xbf), + // Synonym for OP_RETURN + "OP_RETURN_192" => Some(0xc0), + // Synonym for OP_RETURN + "OP_RETURN_193" => Some(0xc1), + // Synonym for OP_RETURN + "OP_RETURN_194" => Some(0xc2), + // Synonym for OP_RETURN + "OP_RETURN_195" => Some(0xc3), + // Synonym for OP_RETURN + "OP_RETURN_196" => Some(0xc4), + // Synonym for OP_RETURN + "OP_RETURN_197" => Some(0xc5), + // Synonym for OP_RETURN + "OP_RETURN_198" => Some(0xc6), + // Synonym for OP_RETURN + "OP_RETURN_199" => Some(0xc7), + // Synonym for OP_RETURN + "OP_RETURN_200" => Some(0xc8), + // Synonym for OP_RETURN + "OP_RETURN_201" => Some(0xc9), + // Synonym for OP_RETURN + "OP_RETURN_202" => Some(0xca), + // Synonym for OP_RETURN + "OP_RETURN_203" => Some(0xcb), + // Synonym for OP_RETURN + "OP_RETURN_204" => Some(0xcc), + // Synonym for OP_RETURN + "OP_RETURN_205" => Some(0xcd), + // Synonym for OP_RETURN + "OP_RETURN_206" => Some(0xce), + // Synonym for OP_RETURN + "OP_RETURN_207" => Some(0xcf), + // Synonym for OP_RETURN + "OP_RETURN_208" => Some(0xd0), + // Synonym for OP_RETURN + "OP_RETURN_209" => Some(0xd1), + // Synonym for OP_RETURN + "OP_RETURN_210" => Some(0xd2), + // Synonym for OP_RETURN + "OP_RETURN_211" => Some(0xd3), + // Synonym for OP_RETURN + "OP_RETURN_212" => Some(0xd4), + // Synonym for OP_RETURN + "OP_RETURN_213" => Some(0xd5), + // Synonym for OP_RETURN + "OP_RETURN_214" => Some(0xd6), + // Synonym for OP_RETURN + "OP_RETURN_215" => Some(0xd7), + // Synonym for OP_RETURN + "OP_RETURN_216" => Some(0xd8), + // Synonym for OP_RETURN + "OP_RETURN_217" => Some(0xd9), + // Synonym for OP_RETURN + "OP_RETURN_218" => Some(0xda), + // Synonym for OP_RETURN + "OP_RETURN_219" => Some(0xdb), + // Synonym for OP_RETURN + "OP_RETURN_220" => Some(0xdc), + // Synonym for OP_RETURN + "OP_RETURN_221" => Some(0xdd), + // Synonym for OP_RETURN + "OP_RETURN_222" => Some(0xde), + // Synonym for OP_RETURN + "OP_RETURN_223" => Some(0xdf), + // Synonym for OP_RETURN + "OP_RETURN_224" => Some(0xe0), + // Synonym for OP_RETURN + "OP_RETURN_225" => Some(0xe1), + // Synonym for OP_RETURN + "OP_RETURN_226" => Some(0xe2), + // Synonym for OP_RETURN + "OP_RETURN_227" => Some(0xe3), + // Synonym for OP_RETURN + "OP_RETURN_228" => Some(0xe4), + // Synonym for OP_RETURN + "OP_RETURN_229" => Some(0xe5), + // Synonym for OP_RETURN + "OP_RETURN_230" => Some(0xe6), + // Synonym for OP_RETURN + "OP_RETURN_231" => Some(0xe7), + // Synonym for OP_RETURN + "OP_RETURN_232" => Some(0xe8), + // Synonym for OP_RETURN + "OP_RETURN_233" => Some(0xe9), + // Synonym for OP_RETURN + "OP_RETURN_234" => Some(0xea), + // Synonym for OP_RETURN + "OP_RETURN_235" => Some(0xeb), + // Synonym for OP_RETURN + "OP_RETURN_236" => Some(0xec), + // Synonym for OP_RETURN + "OP_RETURN_237" => Some(0xed), + // Synonym for OP_RETURN + "OP_RETURN_238" => Some(0xee), + // Synonym for OP_RETURN + "OP_RETURN_239" => Some(0xef), + // Synonym for OP_RETURN + "OP_RETURN_240" => Some(0xf0), + // Synonym for OP_RETURN + "OP_RETURN_241" => Some(0xf1), + // Synonym for OP_RETURN + "OP_RETURN_242" => Some(0xf2), + // Synonym for OP_RETURN + "OP_RETURN_243" => Some(0xf3), + // Synonym for OP_RETURN + "OP_RETURN_244" => Some(0xf4), + // Synonym for OP_RETURN + "OP_RETURN_245" => Some(0xf5), + // Synonym for OP_RETURN + "OP_RETURN_246" => Some(0xf6), + // Synonym for OP_RETURN + "OP_RETURN_247" => Some(0xf7), + // Synonym for OP_RETURN + "OP_RETURN_248" => Some(0xf8), + // Synonym for OP_RETURN + "OP_RETURN_249" => Some(0xf9), + // Synonym for OP_RETURN + "OP_RETURN_250" => Some(0xfa), + // Synonym for OP_RETURN + "OP_RETURN_251" => Some(0xfb), + // Synonym for OP_RETURN + "OP_RETURN_252" => Some(0xfc), + // Synonym for OP_RETURN + "OP_RETURN_253" => Some(0xfd), + // Synonym for OP_RETURN + "OP_RETURN_254" => Some(0xfe), + // Synonym for OP_RETURN + "OP_RETURN_255" => Some(0xff), + _ => None, + } +} diff --git a/components/chainhook-event-observer/src/indexer/bitcoin/blocks_pool.rs b/components/chainhook-event-observer/src/indexer/bitcoin/blocks_pool.rs new file mode 100644 index 0000000..aa998b1 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/bitcoin/blocks_pool.rs @@ -0,0 +1,366 @@ +use crate::{ + indexer::{ChainSegment, ChainSegmentIncompatibility}, + utils::Context, +}; +use chainhook_types::{ + BitcoinBlockData, BitcoinChainEvent, BitcoinChainUpdatedWithBlocksData, + BitcoinChainUpdatedWithReorgData, BlockIdentifier, +}; +use hiro_system_kit::slog; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; + +pub struct BitcoinBlockPool { + canonical_fork_id: usize, + orphans: BTreeSet, + block_store: HashMap, + forks: BTreeMap, +} + +impl BitcoinBlockPool { + pub fn new() -> BitcoinBlockPool { + let mut forks = BTreeMap::new(); + forks.insert(0, ChainSegment::new()); + BitcoinBlockPool { + canonical_fork_id: 0, + block_store: HashMap::new(), + orphans: BTreeSet::new(), + forks, + } + } + + pub fn process_block( + &mut self, + block: BitcoinBlockData, + ctx: &Context, + ) -> Result, String> { + ctx.try_log(|logger| { + slog::info!( + logger, + "Start processing Bitcoin {}", + block.block_identifier + ) + }); + + // Keep block data in memory + let existing_entry = self + .block_store + .insert(block.block_identifier.clone(), block.clone()); + if existing_entry.is_some() { + ctx.try_log(|logger| { + slog::warn!( + logger, + "Bitcoin {} has already been processed", + block.block_identifier + ) + }); + return Ok(None); + } + + for (i, fork) in self.forks.iter() { + ctx.try_log(|logger| slog::info!(logger, "Active fork {}: {}", i, fork)); + } + // Retrieve previous canonical fork + let previous_canonical_fork_id = self.canonical_fork_id; + let previous_canonical_fork = match self.forks.get(&previous_canonical_fork_id) { + Some(fork) => fork.clone(), + None => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to retrieve previous bitcoin fork") + }); + return Ok(None); + } + }; + + let mut fork_updated = None; + for (_, fork) in self.forks.iter_mut() { + let (block_appended, mut new_fork) = fork.try_append_block(&block, ctx); + if block_appended { + if let Some(new_fork) = new_fork.take() { + let fork_id = self.forks.len(); + self.forks.insert(fork_id, new_fork); + fork_updated = self.forks.get_mut(&fork_id); + } else { + fork_updated = Some(fork); + } + // A block can only be added to one segment + break; + } + } + + let fork_updated = match fork_updated.take() { + Some(fork) => { + ctx.try_log(|logger| { + slog::debug!( + logger, + "Bitcoin {} successfully appended to {}", + block.block_identifier, + fork + ) + }); + fork + } + None => { + ctx.try_log(|logger| { + slog::debug!( + logger, + "Unable to process Bitcoin {} - inboxed for later", + block.block_identifier + ) + }); + self.orphans.insert(block.block_identifier.clone()); + return Ok(None); + } + }; + + // Process former orphans + let orphans = self.orphans.clone(); + let mut orphans_to_untrack = HashSet::new(); + + let mut at_least_one_orphan_appended = true; + // As long as we are successful appending blocks that were previously unprocessable, + // Keep looping on this backlog + let mut applied = HashSet::new(); + let mut forks_created = vec![]; + while at_least_one_orphan_appended { + at_least_one_orphan_appended = false; + for orphan_block_identifier in orphans.iter() { + if applied.contains(orphan_block_identifier) { + continue; + } + let block = match self.block_store.get(orphan_block_identifier) { + Some(block) => block.clone(), + None => continue, + }; + + let (orphan_appended, mut new_fork) = fork_updated.try_append_block(&block, ctx); + if orphan_appended { + applied.insert(orphan_block_identifier); + orphans_to_untrack.insert(orphan_block_identifier); + if let Some(new_fork) = new_fork.take() { + forks_created.push(new_fork); + } + } + at_least_one_orphan_appended = at_least_one_orphan_appended || orphan_appended; + } + } + + // Update orphans + for orphan in orphans_to_untrack.into_iter() { + ctx.try_log(|logger| slog::info!(logger, "Dequeuing orphan {}", orphan)); + self.orphans.remove(orphan); + } + + // Select canonical fork + let mut canonical_fork_id = 0; + let mut highest_height = 0; + for (fork_id, fork) in self.forks.iter() { + ctx.try_log(|logger| slog::info!(logger, "Active fork: {} - {}", fork_id, fork)); + if fork.get_length() >= highest_height { + highest_height = fork.get_length(); + canonical_fork_id = *fork_id; + } + } + ctx.try_log(|logger| { + slog::info!( + logger, + "Active fork selected as canonical: {}", + canonical_fork_id + ) + }); + + self.canonical_fork_id = canonical_fork_id; + // Generate chain event from the previous and current canonical forks + let canonical_fork = self.forks.get(&canonical_fork_id).unwrap().clone(); + if canonical_fork.eq(&previous_canonical_fork) { + ctx.try_log(|logger| slog::info!(logger, "Canonical fork unchanged")); + return Ok(None); + } + + let res = self.generate_block_chain_event(&canonical_fork, &previous_canonical_fork, ctx); + let mut chain_event = match res { + Ok(chain_event) => chain_event, + Err(ChainSegmentIncompatibility::ParentBlockUnknown) => { + self.canonical_fork_id = previous_canonical_fork_id; + return Ok(None); + } + _ => return Ok(None), + }; + + self.collect_and_prune_confirmed_blocks(&mut chain_event, ctx); + + Ok(Some(chain_event)) + } + + pub fn collect_and_prune_confirmed_blocks( + &mut self, + chain_event: &mut BitcoinChainEvent, + ctx: &Context, + ) { + let (tip, confirmed_blocks) = match chain_event { + BitcoinChainEvent::ChainUpdatedWithBlocks(ref mut event) => { + match event.new_blocks.last() { + Some(tip) => (tip.block_identifier.clone(), &mut event.confirmed_blocks), + None => return, + } + } + BitcoinChainEvent::ChainUpdatedWithReorg(ref mut event) => { + match event.blocks_to_apply.last() { + Some(tip) => (tip.block_identifier.clone(), &mut event.confirmed_blocks), + None => return, + } + } + }; + + let mut forks_to_prune = vec![]; + let mut ancestor_identifier = &tip; + + // Retrieve the whole canonical segment present in memory, ascending order + // [1] ... [6] [7] + let canonical_segment = { + let mut segment = vec![]; + while let Some(ancestor) = self.block_store.get(&ancestor_identifier) { + ancestor_identifier = &ancestor.parent_block_identifier; + segment.push(ancestor.block_identifier.clone()); + } + segment + }; + if canonical_segment.len() < 7 { + return; + } + // Any block beyond 6th ancestor is considered as confirmed and can be pruned + let cut_off = &canonical_segment[5]; + + // Prune forks using the confirmed block + let mut blocks_to_prune = vec![]; + for (fork_id, fork) in self.forks.iter_mut() { + let mut res = fork.prune_confirmed_blocks(&cut_off); + blocks_to_prune.append(&mut res); + if fork.block_ids.is_empty() { + forks_to_prune.push(*fork_id); + } + } + + // Prune orphans using the confirmed block + let iter = self.orphans.clone().into_iter(); + for orphan in iter { + if orphan.index < cut_off.index { + self.orphans.remove(&orphan); + blocks_to_prune.push(orphan); + } + } + + for confirmed_block in canonical_segment[6..].into_iter() { + let block = match self.block_store.remove(confirmed_block) { + None => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to retrieve data for {}", confirmed_block) + }); + return; + } + Some(block) => block, + }; + confirmed_blocks.push(block); + } + + // Prune data + for block_to_prune in blocks_to_prune { + self.block_store.remove(&block_to_prune); + } + for fork_id in forks_to_prune { + self.forks.remove(&fork_id); + } + confirmed_blocks.reverse(); + } + + pub fn generate_block_chain_event( + &mut self, + canonical_segment: &ChainSegment, + other_segment: &ChainSegment, + ctx: &Context, + ) -> Result { + if other_segment.is_empty() { + let mut new_blocks = vec![]; + for i in 0..canonical_segment.block_ids.len() { + let block_identifier = + &canonical_segment.block_ids[canonical_segment.block_ids.len() - 1 - i]; + let block = match self.block_store.get(block_identifier) { + Some(block) => block.clone(), + None => { + ctx.try_log(|logger| { + slog::error!( + logger, + "unable to retrive Bitcoin {} from block store", + block_identifier + ) + }); + return Err(ChainSegmentIncompatibility::Unknown); + } + }; + new_blocks.push(block) + } + return Ok(BitcoinChainEvent::ChainUpdatedWithBlocks( + BitcoinChainUpdatedWithBlocksData { + new_blocks, + confirmed_blocks: vec![], + }, + )); + } + if let Ok(divergence) = canonical_segment.try_identify_divergence(other_segment, false, ctx) + { + if divergence.blocks_to_rollback.is_empty() { + let mut new_blocks = vec![]; + for i in 0..divergence.blocks_to_apply.len() { + let block_identifier = &divergence.blocks_to_apply[i]; + let block = match self.block_store.get(block_identifier) { + Some(block) => block.clone(), + None => panic!("unable to retrive block from block store"), + }; + new_blocks.push(block) + } + return Ok(BitcoinChainEvent::ChainUpdatedWithBlocks( + BitcoinChainUpdatedWithBlocksData { + new_blocks, + confirmed_blocks: vec![], + }, + )); + } else { + return Ok(BitcoinChainEvent::ChainUpdatedWithReorg( + BitcoinChainUpdatedWithReorgData { + blocks_to_rollback: divergence + .blocks_to_rollback + .iter() + .map(|block_id| { + let block = match self.block_store.get(block_id) { + Some(block) => block.clone(), + None => panic!("unable to retrive block from block store"), + }; + block + }) + .collect::>(), + blocks_to_apply: divergence + .blocks_to_apply + .iter() + .map(|block_id| { + let block = match self.block_store.get(block_id) { + Some(block) => block.clone(), + None => panic!("unable to retrive block from block store"), + }; + block + }) + .collect::>(), + confirmed_blocks: vec![], + }, + )); + } + } + ctx.try_log(|logger| { + slog::debug!( + logger, + "Unable to infer chain event out of {} and {}", + canonical_segment, + other_segment + ) + }); + Err(ChainSegmentIncompatibility::ParentBlockUnknown) + } +} diff --git a/components/chainhook-event-observer/src/indexer/bitcoin/mod.rs b/components/chainhook-event-observer/src/indexer/bitcoin/mod.rs new file mode 100644 index 0000000..8c446df --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/bitcoin/mod.rs @@ -0,0 +1,309 @@ +mod blocks_pool; + +use std::time::Duration; + +use crate::chainhooks::types::{ + get_canonical_magic_bytes, get_canonical_pox_config, PoxConfig, StacksOpcodes, +}; +use crate::indexer::IndexerConfig; +use crate::observer::BitcoinConfig; +use crate::utils::Context; +use bitcoincore_rpc::bitcoin::Block; +pub use blocks_pool::BitcoinBlockPool; +use chainhook_types::bitcoin::{OutPoint, TxIn, TxOut}; +use chainhook_types::{ + BitcoinBlockData, BitcoinBlockMetadata, BitcoinTransactionData, BitcoinTransactionMetadata, + BlockCommitmentData, BlockIdentifier, KeyRegistrationData, LockSTXData, PobBlockCommitmentData, + PoxBlockCommitmentData, PoxReward, StacksBaseChainOperation, TransactionIdentifier, + TransferSTXData, +}; +use clarity_repl::clarity::util::hash::{hex_bytes, to_hex}; +use hiro_system_kit::slog; +use rocket::serde::json::Value as JsonValue; + +#[derive(Deserialize)] +pub struct NewBitcoinBlock { + pub burn_block_hash: String, + pub burn_block_height: u64, + pub reward_slot_holders: Vec, + pub reward_recipients: Vec, + pub burn_amount: u64, +} + +#[allow(dead_code)] +#[derive(Deserialize)] +pub struct RewardParticipant { + recipient: String, + amt: u64, +} + +pub async fn retrieve_full_block( + bitcoin_config: &BitcoinConfig, + marshalled_block: JsonValue, + _ctx: &Context, +) -> Result<(u64, Block), String> { + let partial_block: NewBitcoinBlock = serde_json::from_value(marshalled_block) + .map_err(|e| format!("unable for parse bitcoin block: {}", e.to_string()))?; + let block_hash = partial_block.burn_block_hash.strip_prefix("0x").unwrap(); + + use reqwest::Client as HttpClient; + let body = json!({ + "jsonrpc": "1.0", + "id": "chainhook-cli", + "method": "getblock", + "params": [block_hash, 0] + }); + let http_client = HttpClient::builder() + .timeout(Duration::from_secs(20)) + .build() + .expect("Unable to build http client"); + let response_hex = http_client + .post(&bitcoin_config.rpc_url) + .basic_auth(&bitcoin_config.username, Some(&bitcoin_config.password)) + .header("Content-Type", "application/json") + .header("Host", &bitcoin_config.rpc_url[7..]) + .json(&body) + .send() + .await + .map_err(|e| format!("unable to send request ({})", e))? + .json::() + .await + .map_err(|e| format!("unable to parse response ({})", e))? + .result::() + .map_err(|e| format!("unable to parse response ({})", e))?; + + let bytes = hex_bytes(&response_hex) + .map_err(|e| format!("unable to retrieve bytes from response ({})", e))?; + + let block = bitcoincore_rpc::bitcoin::consensus::encode::deserialize(&bytes) + .map_err(|e| format!("unable to deserialize bitcoin block ({})", e))?; + + let block_height = partial_block.burn_block_height; + Ok((block_height, block)) +} + +pub fn standardize_bitcoin_block( + indexer_config: &IndexerConfig, + block_height: u64, + block: Block, + ctx: &Context, +) -> Result { + let mut transactions = vec![]; + + let expected_magic_bytes = get_canonical_magic_bytes(&indexer_config.bitcoin_network); + let pox_config = get_canonical_pox_config(&indexer_config.bitcoin_network); + + for mut tx in block.txdata.into_iter() { + let txid = tx.txid().to_string(); + let mut inputs = vec![]; + for input in tx.input.drain(..) { + inputs.push(TxIn { + previous_output: OutPoint { + txid: input.previous_output.txid.to_string(), + vout: input.previous_output.vout, + }, + script_sig: to_hex(input.script_sig.as_bytes()), + sequence: input.sequence.0, + witness: input + .witness + .to_vec() + .iter() + .map(|w| format!("0x{}", to_hex(w))) + .collect::>(), + }) + } + + let mut outputs = vec![]; + let mut stacks_operations = vec![]; + + if let Some(op) = try_parse_stacks_operation( + &tx.output, + &pox_config, + &expected_magic_bytes, + block_height, + ctx, + ) { + stacks_operations.push(op); + } + + for output in tx.output.drain(..) { + outputs.push(TxOut { + value: output.value, + script_pubkey: to_hex(output.script_pubkey.as_bytes()), + }); + } + + let tx = BitcoinTransactionData { + transaction_identifier: TransactionIdentifier { + hash: format!("0x{}", txid), + }, + operations: vec![], + metadata: BitcoinTransactionMetadata { + inputs, + outputs, + stacks_operations, + proof: None, + }, + }; + transactions.push(tx); + } + + Ok(BitcoinBlockData { + block_identifier: BlockIdentifier { + hash: format!("0x{}", block.header.block_hash().to_string()), + index: block_height, + }, + parent_block_identifier: BlockIdentifier { + hash: format!("0x{}", block.header.prev_blockhash.to_string()), + index: block_height - 1, + }, + timestamp: block.header.time, + metadata: BitcoinBlockMetadata {}, + transactions, + }) +} + +fn try_parse_stacks_operation( + outputs: &Vec, + pox_config: &PoxConfig, + expected_magic_bytes: &[u8; 2], + block_height: u64, + ctx: &Context, +) -> Option { + if outputs.is_empty() { + return None; + } + + if !outputs[0].script_pubkey.is_op_return() { + return None; + } + + // Safely parsing the first 2 bytes (following OP_RETURN + PUSH_DATA) + let op_return_output = outputs[0].script_pubkey.as_bytes(); + if op_return_output.len() < 7 { + return None; + } + if op_return_output[3] != expected_magic_bytes[0] + || op_return_output[4] != expected_magic_bytes[1] + { + return None; + } + // Safely classifying the Stacks operation; + let op_type: StacksOpcodes = match op_return_output[5].try_into() { + Ok(op) => op, + Err(_) => { + ctx.try_log(|logger| { + slog::debug!( + logger, + "Stacks operation parsing - opcode unknown {}", + op_return_output[5] + ) + }); + return None; + } + }; + let op = match op_type { + StacksOpcodes::KeyRegister => { + let res = try_parse_key_register_op(&op_return_output[6..])?; + StacksBaseChainOperation::KeyRegistration(res) + } + StacksOpcodes::PreStx => { + let _ = try_parse_pre_stx_op(&op_return_output[6..])?; + return None; + } + StacksOpcodes::TransferStx => { + let res = try_parse_transfer_stx_op(&op_return_output[6..])?; + StacksBaseChainOperation::TransferSTX(res) + } + StacksOpcodes::StackStx => { + let res = try_parse_stacks_stx_op(&op_return_output[6..])?; + StacksBaseChainOperation::LockSTX(res) + } + StacksOpcodes::BlockCommit => { + let res = try_parse_block_commit_op(&op_return_output[5..])?; + // We need to determine wether the transaction was a PoB or a Pox commitment + if pox_config.is_consensus_rewarding_participants_at_block_height(block_height) { + if outputs.len() < 1 + pox_config.rewarded_addresses_per_block { + return None; + } + let mut rewards = vec![]; + for output in outputs[1..pox_config.rewarded_addresses_per_block].into_iter() { + rewards.push(PoxReward { + recipient: output.script_pubkey.to_string(), + amount: output.value, + }); + } + StacksBaseChainOperation::PoxBlockCommitment(PoxBlockCommitmentData { + signers: vec![], // todo(lgalabru) + stacks_block_hash: res.stacks_block_hash.clone(), + rewards, + }) + } else { + if outputs.len() < 2 { + return None; + } + let amount = outputs[1].value; + StacksBaseChainOperation::PobBlockCommitment(PobBlockCommitmentData { + signers: vec![], // todo(lgalabru) + stacks_block_hash: res.stacks_block_hash.clone(), + amount, + }) + } + } + }; + + Some(op) +} + +fn try_parse_block_commit_op(bytes: &[u8]) -> Option { + if bytes.len() < 32 { + return None; + } + + Some(BlockCommitmentData { + stacks_block_hash: format!("0x{}", to_hex(&bytes[0..32])), + }) +} + +fn try_parse_key_register_op(_bytes: &[u8]) -> Option { + Some(KeyRegistrationData {}) +} + +fn try_parse_pre_stx_op(_bytes: &[u8]) -> Option<()> { + None +} + +fn try_parse_transfer_stx_op(bytes: &[u8]) -> Option { + if bytes.len() < 16 { + return None; + } + + // todo(lgalabru) + Some(TransferSTXData { + sender: "".into(), + recipient: "".into(), + amount: "".into(), + }) +} + +fn try_parse_stacks_stx_op(bytes: &[u8]) -> Option { + if bytes.len() < 16 { + return None; + } + + // todo(lgalabru) + Some(LockSTXData { + sender: "".into(), + amount: "".into(), + duration: 1, + }) +} + +#[cfg(test)] +pub mod tests; + +// Test vectors +// 1) Devnet PoB +// 2022-10-26T03:06:17.376341Z INFO chainhook_event_observer::indexer: BitcoinBlockData { block_identifier: BlockIdentifier { index: 104, hash: "0x210d0d095a75d88fc059cb97f453eee33b1833153fb1f81b9c3c031c26bb106b" }, parent_block_identifier: BlockIdentifier { index: 103, hash: "0x5d5a4b8113c35f20fb0b69b1fb1ae1b88461ea57e2a2e4c036f97fae70ca1abb" }, timestamp: 1666753576, transactions: [BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xfaaac1833dc4883e7ec28f61e35b41f896c395f8d288b1a177155de2abd6052f" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "0000000000000000000000000000000000000000000000000000000000000000", vout: 4294967295 }, script_sig: "01680101", sequence: 4294967295, witness: [] }], outputs: [TxOut { value: 5000017550, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }, TxOut { value: 0, script_pubkey: "6a24aa21a9ed4a190dfdc77e260409c2a693e6d3b8eca43afbc4bffb79ddcdcc9516df804d9b" }], stacks_operations: [] } }, BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0x59193c24cb2325cd2271b89f790f958dcd4065088680ffbc201a0ebb2f3cbf25" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "9eebe848baaf8dd4810e4e4a91168e2e471c949439faf5d768750ca21d067689", vout: 3 }, script_sig: "483045022100a20f90e9e3c3bb7e558ad4fa65902d8cf6ce4bff1f5af0ac0a323b547385069c022021b9877abbc9d1eef175c7f712ac1b2d8f5ce566be542714effe42711e75b83801210239810ebf35e6f6c26062c99f3e183708d377720617c90a986859ec9c95d00be9", sequence: 4294967293, witness: [] }], outputs: [TxOut { value: 0, script_pubkey: "6a4c5069645b1681995f8e568287e0e4f5cbc1d6727dafb5e3a7822a77c69bd04208265aca9424d0337dac7d9e84371a2c91ece1891d67d3554bd9fdbe60afc6924d4b0773d90000006700010000006600012b" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 4999904850, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }], stacks_operations: [PobBlockCommitment(PobBlockCommitmentData { signers: [], stacks_block_hash: "0x5b1681995f8e568287e0e4f5cbc1d6727dafb5e3a7822a77c69bd04208265aca", amount: 10000 })] } }], metadata: BitcoinBlockMetadata } +// 2022-10-26T03:06:21.929157Z INFO chainhook_event_observer::indexer: BitcoinBlockData { block_identifier: BlockIdentifier { index: 105, hash: "0x0302c4c6063eb7199d3a565351bceeea9df4cb4aa09293194dbab277e46c2979" }, parent_block_identifier: BlockIdentifier { index: 104, hash: "0x210d0d095a75d88fc059cb97f453eee33b1833153fb1f81b9c3c031c26bb106b" }, timestamp: 1666753581, transactions: [BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xe7de433aa89c1f946f89133b0463b6cfebb26ad73b0771a79fd66c6acbfe3fb9" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "0000000000000000000000000000000000000000000000000000000000000000", vout: 4294967295 }, script_sig: "01690101", sequence: 4294967295, witness: [] }], outputs: [TxOut { value: 5000017600, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }, TxOut { value: 0, script_pubkey: "6a24aa21a9ed98ac3bc4e0c9ed53e3418a3bf3aa511dcd76088cf0e1c4fc71fb9755840d7a08" }], stacks_operations: [] } }, BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xe654501805d80d59ef0d95b57ad7a924f3be4a4dc0db5a785dfebe1f70c4e23e" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "59193c24cb2325cd2271b89f790f958dcd4065088680ffbc201a0ebb2f3cbf25", vout: 3 }, script_sig: "483045022100b59d2d07f68ea3a4f27a49979080a07b2432cfad9fc90e1edd0241496f0fd83f02205ac233f4cb68ada487f16339abedb7093948b683ba7d76b3b4058b2c0181a68901210239810ebf35e6f6c26062c99f3e183708d377720617c90a986859ec9c95d00be9", sequence: 4294967293, witness: [] }], outputs: [TxOut { value: 0, script_pubkey: "6a4c5069645b351bb015ef4f7dcdce4c9d95cbf157f85a3714626252cfc9078f3f1591ccdb13c3c7e22b34c4ffc2f6064a41df6fcd7f1b759d4f28b2f7cb6b27f283c868406e0000006800010000006600012c" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 10000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 4999867250, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }], stacks_operations: [PobBlockCommitment(PobBlockCommitmentData { signers: [], stacks_block_hash: "0x5b351bb015ef4f7dcdce4c9d95cbf157f85a3714626252cfc9078f3f1591ccdb", amount: 10000 })] } }], metadata: BitcoinBlockMetadata } +// 2022-10-26T03:07:53.298531Z INFO chainhook_event_observer::indexer: BitcoinBlockData { block_identifier: BlockIdentifier { index: 106, hash: "0x52eb2aa15aa99afc4b918a552cef13e8b6eed84b257be097ad954b4f37a7e98d" }, parent_block_identifier: BlockIdentifier { index: 105, hash: "0x0302c4c6063eb7199d3a565351bceeea9df4cb4aa09293194dbab277e46c2979" }, timestamp: 1666753672, transactions: [BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0xd28d7f5411416f94b95e9f999d5ee8ded5543ba9daae9f612b80f01c5107862d" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "0000000000000000000000000000000000000000000000000000000000000000", vout: 4294967295 }, script_sig: "016a0101", sequence: 4294967295, witness: [] }], outputs: [TxOut { value: 5000017500, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }, TxOut { value: 0, script_pubkey: "6a24aa21a9ed71aaf7e5384879a1b112bf623ac8b46dd88b39c3d2c6f8a1d264fc4463e6356a" }], stacks_operations: [] } }, BitcoinTransactionData { transaction_identifier: TransactionIdentifier { hash: "0x72e8e43afc4362cf921ccc57fde3e07b4cb6fac5f306525c86d38234c18e21d1" }, operations: [], metadata: BitcoinTransactionMetadata { inputs: [TxIn { previous_output: OutPoint { txid: "e654501805d80d59ef0d95b57ad7a924f3be4a4dc0db5a785dfebe1f70c4e23e", vout: 3 }, script_sig: "4730440220798bb7d7fb14df35610db2ef04e5d5b6588440b7c429bf650a96f8570904052b02204a817e13e7296a24a8f6cc8737bddb55d1835e513ec2b9dcb03424e4536ae34c01210239810ebf35e6f6c26062c99f3e183708d377720617c90a986859ec9c95d00be9", sequence: 4294967293, witness: [] }], outputs: [TxOut { value: 0, script_pubkey: "6a4c5069645b504d310fc27c86a6b65d0b0e0297db1e185d3432fdab9fa96a1053407ed07b537b8b7d23c6309dfd24340e85b75cff11ad685f8b310c1d2098748a0fffb146ec00000069000100000066000128" }, TxOut { value: 20000, script_pubkey: "76a914000000000000000000000000000000000000000088ac" }, TxOut { value: 4999829750, script_pubkey: "76a914ee9369fb719c0ba43ddf4d94638a970b84775f4788ac" }], stacks_operations: [PobBlockCommitment(PobBlockCommitmentData { signers: [], stacks_block_hash: "0x5b504d310fc27c86a6b65d0b0e0297db1e185d3432fdab9fa96a1053407ed07b", amount: 20000 })] } }], metadata: BitcoinBlockMetadata } diff --git a/components/chainhook-event-observer/src/indexer/bitcoin/tests.rs b/components/chainhook-event-observer/src/indexer/bitcoin/tests.rs new file mode 100644 index 0000000..b43dcf4 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/bitcoin/tests.rs @@ -0,0 +1,206 @@ +use super::super::tests::{helpers, process_bitcoin_blocks_and_check_expectations}; + +#[test] +fn test_bitcoin_vector_001() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_001()); +} + +#[test] +fn test_bitcoin_vector_002() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_002()); +} + +#[test] +fn test_bitcoin_vector_003() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_003()); +} + +#[test] +fn test_bitcoin_vector_004() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_004()); +} + +#[test] +fn test_bitcoin_vector_005() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_005()); +} + +#[test] +fn test_bitcoin_vector_006() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_006()); +} + +#[test] +fn test_bitcoin_vector_007() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_007()); +} + +#[test] +fn test_bitcoin_vector_008() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_008()); +} + +#[test] +fn test_bitcoin_vector_009() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_009()); +} + +#[test] +fn test_bitcoin_vector_010() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_010()); +} + +#[test] +fn test_bitcoin_vector_011() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_011()); +} + +#[test] +fn test_bitcoin_vector_012() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_012()); +} + +#[test] +fn test_bitcoin_vector_013() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_013()); +} + +#[test] +fn test_bitcoin_vector_014() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_014()); +} + +#[test] +fn test_bitcoin_vector_015() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_015()); +} + +#[test] +fn test_bitcoin_vector_016() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_016()); +} + +#[test] +fn test_bitcoin_vector_017() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_017()); +} + +#[test] +fn test_bitcoin_vector_018() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_018()); +} + +#[test] +fn test_bitcoin_vector_019() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_019()); +} + +#[test] +fn test_bitcoin_vector_020() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_020()); +} + +#[test] +fn test_bitcoin_vector_021() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_021()); +} + +#[test] +fn test_bitcoin_vector_022() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_022()); +} + +#[test] +fn test_bitcoin_vector_023() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_023()); +} + +#[test] +fn test_bitcoin_vector_024() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_024()); +} + +#[test] +fn test_bitcoin_vector_025() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_025()); +} + +#[test] +fn test_bitcoin_vector_026() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_026()); +} + +#[test] +fn test_bitcoin_vector_027() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_027()); +} + +#[test] +fn test_bitcoin_vector_028() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_028()); +} + +#[test] +fn test_bitcoin_vector_029() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_029()); +} + +#[test] +fn test_bitcoin_vector_030() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_030()); +} + +#[test] +fn test_bitcoin_vector_031() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_031()); +} + +#[test] +fn test_bitcoin_vector_032() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_032()); +} + +#[test] +fn test_bitcoin_vector_033() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_033()); +} + +#[test] +fn test_bitcoin_vector_034() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_034()); +} + +#[test] +fn test_bitcoin_vector_035() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_035()); +} + +#[test] +fn test_bitcoin_vector_036() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_036()); +} + +#[test] +fn test_bitcoin_vector_037() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_037()); +} + +#[test] +fn test_bitcoin_vector_038() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_038()); +} + +#[test] +fn test_bitcoin_vector_039() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_039()); +} + +#[test] +fn test_bitcoin_vector_040() { + process_bitcoin_blocks_and_check_expectations(helpers::bitcoin_shapes::get_vector_040()); +} + +// #[test] +// fn test_bitcoin_vector_041() { +// process_bitcoin_blocks_and_check_expectations(helpers::shapes::get_vector_041()); +// } diff --git a/components/chainhook-event-observer/src/indexer/mod.rs b/components/chainhook-event-observer/src/indexer/mod.rs new file mode 100644 index 0000000..50c84df --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/mod.rs @@ -0,0 +1,385 @@ +pub mod bitcoin; +pub mod stacks; + +use crate::utils::{AbstractBlock, Context}; +use bitcoincore_rpc::bitcoin::Block; +use chainhook_types::{ + BitcoinChainEvent, BitcoinNetwork, BlockIdentifier, StacksChainEvent, StacksNetwork, +}; +use hiro_system_kit::slog; +use rocket::serde::json::Value as JsonValue; +use stacks::StacksBlockPool; +use stacks_rpc_client::PoxInfo; +use std::collections::{HashMap, VecDeque}; + +use self::bitcoin::BitcoinBlockPool; + +#[derive(Deserialize, Debug, Clone, Default)] +pub struct AssetClassCache { + pub symbol: String, + pub decimals: u8, +} + +pub struct StacksChainContext { + asset_class_map: HashMap, + pox_info: PoxInfo, +} + +impl StacksChainContext { + pub fn new() -> StacksChainContext { + StacksChainContext { + asset_class_map: HashMap::new(), + pox_info: PoxInfo::default(), + } + } +} + +#[derive(Debug, Clone)] +pub struct IndexerConfig { + pub bitcoin_network: BitcoinNetwork, + pub stacks_network: StacksNetwork, + pub stacks_node_rpc_url: String, + pub bitcoin_node_rpc_url: String, + pub bitcoin_node_rpc_username: String, + pub bitcoin_node_rpc_password: String, +} + +pub struct Indexer { + pub config: IndexerConfig, + stacks_blocks_pool: StacksBlockPool, + bitcoin_blocks_pool: BitcoinBlockPool, + pub stacks_context: StacksChainContext, +} + +impl Indexer { + pub fn new(config: IndexerConfig) -> Indexer { + let stacks_blocks_pool = StacksBlockPool::new(); + let bitcoin_blocks_pool = BitcoinBlockPool::new(); + let stacks_context = StacksChainContext::new(); + Indexer { + config, + stacks_blocks_pool, + bitcoin_blocks_pool, + stacks_context, + } + } + + pub fn handle_bitcoin_block( + &mut self, + block_height: u64, + block: Block, + ctx: &Context, + ) -> Result, String> { + let block = bitcoin::standardize_bitcoin_block(&self.config, block_height, block, ctx)?; + let event = self.bitcoin_blocks_pool.process_block(block, ctx); + event + } + + pub fn handle_stacks_marshalled_block( + &mut self, + marshalled_block: JsonValue, + ctx: &Context, + ) -> Result, String> { + let block = stacks::standardize_stacks_marshalled_block( + &self.config, + marshalled_block, + &mut self.stacks_context, + ctx, + )?; + self.stacks_blocks_pool.process_block(block, ctx) + } + + pub fn handle_stacks_serialized_microblock_trail( + &mut self, + serialized_microblock_trail: &str, + ctx: &Context, + ) -> Result, String> { + let microblocks = stacks::standardize_stacks_serialized_microblock_trail( + &self.config, + serialized_microblock_trail, + &mut self.stacks_context, + ctx, + )?; + self.stacks_blocks_pool + .process_microblocks(microblocks, ctx) + } + + pub fn handle_stacks_marshalled_microblock_trail( + &mut self, + marshalled_microblock_trail: JsonValue, + ctx: &Context, + ) -> Result, String> { + let microblocks = stacks::standardize_stacks_marshalled_microblock_trail( + &self.config, + marshalled_microblock_trail, + &mut self.stacks_context, + ctx, + )?; + self.stacks_blocks_pool + .process_microblocks(microblocks, ctx) + } + + pub fn get_pox_info(&mut self) -> PoxInfo { + self.stacks_context.pox_info.clone() + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChainSegment { + pub amount_of_btc_spent: u64, + pub most_recent_confirmed_block_height: u64, + pub block_ids: VecDeque, + confirmed_blocks_inbox: Vec, +} + +#[derive(Clone, Debug)] +pub enum ChainSegmentIncompatibility { + OutdatedBlock, + OutdatedSegment, + BlockCollision, + ParentBlockUnknown, + AlreadyPresent, + Unknown, +} + +#[derive(Debug)] +pub struct ChainSegmentDivergence { + blocks_to_apply: Vec, + blocks_to_rollback: Vec, +} + +impl ChainSegment { + pub fn new() -> ChainSegment { + let block_ids = VecDeque::new(); + ChainSegment { + block_ids, + most_recent_confirmed_block_height: 0, + confirmed_blocks_inbox: vec![], + amount_of_btc_spent: 0, + } + } + + fn is_empty(&self) -> bool { + self.block_ids.is_empty() + } + + fn is_block_id_older_than_segment(&self, block_identifier: &BlockIdentifier) -> bool { + block_identifier.index < self.most_recent_confirmed_block_height + } + + fn is_block_id_newer_than_segment(&self, block_identifier: &BlockIdentifier) -> bool { + if let Some(tip) = self.block_ids.front() { + return block_identifier.index > (tip.index + 1); + } + return false; + } + + fn get_relative_index(&self, block_identifier: &BlockIdentifier) -> usize { + if let Some(tip) = self.block_ids.front() { + let segment_index = tip.index.saturating_sub(block_identifier.index); + return segment_index.try_into().unwrap(); + } + return 0; + } + + fn can_append_block( + &self, + block: &dyn AbstractBlock, + ctx: &Context, + ) -> Result<(), ChainSegmentIncompatibility> { + if self.is_block_id_older_than_segment(&block.get_identifier()) { + // Could be facing a deep fork... + return Err(ChainSegmentIncompatibility::OutdatedBlock); + } + if self.is_block_id_newer_than_segment(&block.get_identifier()) { + // Chain segment looks outdated, we should just prune it? + return Err(ChainSegmentIncompatibility::OutdatedSegment); + } + let tip = match self.block_ids.front() { + Some(tip) => tip, + None => return Ok(()), + }; + ctx.try_log(|logger| { + slog::info!(logger, "Comparing {} with {}", tip, block.get_identifier()) + }); + if tip.index == block.get_parent_identifier().index { + match tip.hash == block.get_parent_identifier().hash { + true => return Ok(()), + false => return Err(ChainSegmentIncompatibility::ParentBlockUnknown), + } + } + if let Some(colliding_block) = self.get_block_id(&block.get_identifier(), ctx) { + match colliding_block.eq(&block.get_identifier()) { + true => return Err(ChainSegmentIncompatibility::AlreadyPresent), + false => return Err(ChainSegmentIncompatibility::BlockCollision), + } + } + Err(ChainSegmentIncompatibility::Unknown) + } + + fn get_block_id(&self, block_id: &BlockIdentifier, _ctx: &Context) -> Option<&BlockIdentifier> { + match self.block_ids.get(self.get_relative_index(block_id)) { + Some(res) => Some(res), + None => None, + } + } + + pub fn append_block_identifier(&mut self, block_identifier: &BlockIdentifier) { + self.block_ids.push_front(block_identifier.clone()); + } + + pub fn prune_confirmed_blocks(&mut self, cut_off: &BlockIdentifier) -> Vec { + let mut keep = vec![]; + let mut prune = vec![]; + + for block_id in self.block_ids.drain(..) { + if block_id.index >= cut_off.index { + keep.push(block_id); + } else { + prune.push(block_id); + } + } + for block_id in keep.into_iter() { + self.block_ids.push_back(block_id); + } + prune + } + + pub fn get_tip(&self) -> &BlockIdentifier { + self.block_ids.front().unwrap() + } + + pub fn get_length(&self) -> u64 { + let len: u64 = self.block_ids.len().try_into().unwrap(); + self.most_recent_confirmed_block_height + len + } + + pub fn keep_blocks_from_oldest_to_block_identifier( + &mut self, + block_identifier: &BlockIdentifier, + ) -> (bool, bool) { + let mut mutated = false; + loop { + match self.block_ids.pop_front() { + Some(tip) => { + if tip.eq(&block_identifier) { + self.block_ids.push_front(tip); + break (true, mutated); + } + } + _ => break (false, mutated), + } + mutated = true; + } + } + + fn try_identify_divergence( + &self, + other_segment: &ChainSegment, + allow_reset: bool, + ctx: &Context, + ) -> Result { + let mut common_root = None; + let mut blocks_to_rollback = vec![]; + let mut blocks_to_apply = vec![]; + for cursor_segment_1 in other_segment.block_ids.iter() { + blocks_to_apply.clear(); + for cursor_segment_2 in self.block_ids.iter() { + if cursor_segment_2.eq(cursor_segment_1) { + common_root = Some(cursor_segment_2.clone()); + break; + } + blocks_to_apply.push(cursor_segment_2.clone()); + } + if common_root.is_some() { + break; + } + blocks_to_rollback.push(cursor_segment_1.clone()); + } + ctx.try_log(|logger| slog::debug!(logger, "Blocks to rollback: {:?}", blocks_to_rollback)); + ctx.try_log(|logger| slog::debug!(logger, "Blocks to apply: {:?}", blocks_to_apply)); + blocks_to_rollback.reverse(); + blocks_to_apply.reverse(); + match common_root.take() { + Some(_common_root) => Ok(ChainSegmentDivergence { + blocks_to_rollback, + blocks_to_apply, + }), + None if allow_reset => Ok(ChainSegmentDivergence { + blocks_to_rollback, + blocks_to_apply, + }), + None => Err(ChainSegmentIncompatibility::Unknown), + } + } + + fn try_append_block( + &mut self, + block: &dyn AbstractBlock, + ctx: &Context, + ) -> (bool, Option) { + let mut block_appended = false; + let mut fork = None; + ctx.try_log(|logger| { + slog::info!( + logger, + "Trying to append {} to {}", + block.get_identifier(), + self + ) + }); + match self.can_append_block(block, ctx) { + Ok(()) => { + self.append_block_identifier(&block.get_identifier()); + block_appended = true; + } + Err(incompatibility) => { + ctx.try_log(|logger| { + slog::info!(logger, "Will have to fork: {:?}", incompatibility) + }); + match incompatibility { + ChainSegmentIncompatibility::BlockCollision => { + let mut new_fork = self.clone(); + let (parent_found, _) = new_fork + .keep_blocks_from_oldest_to_block_identifier( + &block.get_parent_identifier(), + ); + if parent_found { + ctx.try_log(|logger| slog::info!(logger, "Success")); + new_fork.append_block_identifier(&block.get_identifier()); + fork = Some(new_fork); + block_appended = true; + } + } + ChainSegmentIncompatibility::OutdatedSegment => { + // TODO(lgalabru): test depth + // fork_ids_to_prune.push(fork_id); + } + ChainSegmentIncompatibility::ParentBlockUnknown => {} + ChainSegmentIncompatibility::OutdatedBlock => {} + ChainSegmentIncompatibility::Unknown => {} + ChainSegmentIncompatibility::AlreadyPresent => {} + } + } + } + (block_appended, fork) + } +} + +impl std::fmt::Display for ChainSegment { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!( + f, + "Fork [{}], height = {}", + self.block_ids + .iter() + .map(|b| format!("{}", b)) + .collect::>() + .join(", "), + self.get_length() + ) + } +} + +#[cfg(test)] +pub mod tests; diff --git a/components/chainhook-event-observer/src/indexer/stacks/blocks_pool.rs b/components/chainhook-event-observer/src/indexer/stacks/blocks_pool.rs new file mode 100644 index 0000000..9daae3d --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/stacks/blocks_pool.rs @@ -0,0 +1,1018 @@ +use crate::{ + indexer::{ChainSegment, ChainSegmentIncompatibility}, + utils::Context, +}; +use chainhook_types::{ + BlockIdentifier, StacksBlockData, StacksBlockUpdate, StacksChainEvent, + StacksChainUpdatedWithBlocksData, StacksChainUpdatedWithMicroblocksData, + StacksChainUpdatedWithMicroblocksReorgData, StacksChainUpdatedWithReorgData, + StacksMicroblockData, +}; +use hiro_system_kit::slog; +use std::collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap, HashSet}; + +pub struct StacksBlockPool { + canonical_fork_id: usize, + orphans: BTreeSet, + block_store: HashMap, + forks: BTreeMap, + microblock_store: HashMap<(BlockIdentifier, BlockIdentifier), StacksMicroblockData>, + micro_forks: HashMap>, + micro_orphans: BTreeSet<(BlockIdentifier, BlockIdentifier)>, + canonical_micro_fork_id: HashMap, +} + +impl StacksBlockPool { + pub fn new() -> StacksBlockPool { + let mut forks = BTreeMap::new(); + forks.insert(0, ChainSegment::new()); + StacksBlockPool { + canonical_fork_id: 0, + block_store: HashMap::new(), + orphans: BTreeSet::new(), + forks, + microblock_store: HashMap::new(), + micro_forks: HashMap::new(), + micro_orphans: BTreeSet::new(), + canonical_micro_fork_id: HashMap::new(), + } + } + + pub fn process_block( + &mut self, + block: StacksBlockData, + ctx: &Context, + ) -> Result, String> { + ctx.try_log(|logger| { + slog::info!(logger, "Start processing Stacks {}", block.block_identifier) + }); + + // Keep block data in memory + let existing_entry = self + .block_store + .insert(block.block_identifier.clone(), block.clone()); + if existing_entry.is_some() { + ctx.try_log(|logger| { + slog::warn!( + logger, + "Stacks {} has already been processed", + block.block_identifier + ) + }); + return Ok(None); + } + + for (i, fork) in self.forks.iter() { + ctx.try_log(|logger| slog::info!(logger, "Active fork {}: {}", i, fork)); + } + // Retrieve previous canonical fork + let previous_canonical_fork_id = self.canonical_fork_id; + let previous_canonical_fork = match self.forks.get(&previous_canonical_fork_id) { + Some(fork) => fork.clone(), + None => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to retrieve previous stacks fork") + }); + return Ok(None); + } + }; + + let mut fork_updated = None; + for (_, fork) in self.forks.iter_mut() { + let (block_appended, mut new_fork) = fork.try_append_block(&block, ctx); + if block_appended { + if let Some(new_fork) = new_fork.take() { + let number_of_forks = self.forks.len(); + let mut next_fork_id = 0; + for (index, (fork_id, _)) in self.forks.iter().enumerate() { + if (index + 1) == number_of_forks { + next_fork_id = fork_id + 1; + } + } + self.forks.insert(next_fork_id, new_fork); + fork_updated = self.forks.get_mut(&next_fork_id); + } else { + fork_updated = Some(fork); + } + // A block can only be added to one segment + break; + } + } + + let fork_updated = match fork_updated.take() { + Some(fork) => { + ctx.try_log(|logger| { + slog::info!( + logger, + "Stacks {} successfully appended to {}", + block.block_identifier, + fork + ) + }); + fork + } + None => { + ctx.try_log(|logger| { + slog::error!( + logger, + "Unable to process Stacks {} - inboxed for later", + block.block_identifier + ) + }); + self.orphans.insert(block.block_identifier.clone()); + return Ok(None); + } + }; + + // Process former orphans + let orphans = self.orphans.clone(); + let mut orphans_to_untrack = HashSet::new(); + + let mut at_least_one_orphan_appended = true; + // As long as we are successful appending blocks that were previously unprocessable, + // Keep looping on this backlog + let mut applied = HashSet::new(); + while at_least_one_orphan_appended { + at_least_one_orphan_appended = false; + for orphan_block_identifier in orphans.iter() { + if applied.contains(orphan_block_identifier) { + continue; + } + let block = match self.block_store.get(orphan_block_identifier) { + Some(block) => block.clone(), + None => continue, + }; + + let (orphan_appended, _new_fork) = fork_updated.try_append_block(&block, ctx); + if orphan_appended { + applied.insert(orphan_block_identifier); + orphans_to_untrack.insert(orphan_block_identifier); + } + at_least_one_orphan_appended = at_least_one_orphan_appended || orphan_appended; + } + } + + // Update orphans + for orphan in orphans_to_untrack.into_iter() { + ctx.try_log(|logger| slog::info!(logger, "Dequeuing orphan {}", orphan)); + self.orphans.remove(orphan); + } + + // Select canonical fork + let mut canonical_fork_id = 0; + let mut highest_height = 0; + let mut highest_bitcoin_height = 0; + for (fork_id, fork) in self.forks.iter() { + let tip_bitcoin_height = self + .block_store + .get(fork.get_tip()) + .map(|b| b.metadata.bitcoin_anchor_block_identifier.index) + .unwrap_or(0); + ctx.try_log(|logger| { + slog::info!( + logger, + "Active fork: {} - {} / {}", + fork_id, + fork, + tip_bitcoin_height + ) + }); + if tip_bitcoin_height > highest_bitcoin_height + || (tip_bitcoin_height == highest_bitcoin_height && fork_id > &canonical_fork_id) + { + highest_bitcoin_height = tip_bitcoin_height; + let tip_height = fork.get_tip().index; + if tip_height >= highest_height { + highest_height = tip_height; + canonical_fork_id = *fork_id; + } + } + } + ctx.try_log(|logger| { + slog::info!( + logger, + "Active fork selected as canonical: {}", + canonical_fork_id + ) + }); + + self.canonical_fork_id = canonical_fork_id; + // Generate chain event from the previous and current canonical forks + let canonical_fork = self.forks.get(&canonical_fork_id).unwrap().clone(); + if canonical_fork.eq(&previous_canonical_fork) { + ctx.try_log(|logger| slog::info!(logger, "Canonical fork unchanged")); + return Ok(None); + } + + let res = self.generate_block_chain_event(&canonical_fork, &previous_canonical_fork, ctx); + let mut chain_event = match res { + Ok(chain_event) => chain_event, + Err(ChainSegmentIncompatibility::ParentBlockUnknown) => { + self.canonical_fork_id = previous_canonical_fork_id; + return Ok(None); + } + _ => return Ok(None), + }; + + self.collect_and_prune_confirmed_blocks(&mut chain_event, ctx); + + Ok(Some(chain_event)) + } + + pub fn collect_and_prune_confirmed_blocks( + &mut self, + chain_event: &mut StacksChainEvent, + ctx: &Context, + ) { + let (tip, confirmed_blocks) = match chain_event { + StacksChainEvent::ChainUpdatedWithBlocks(ref mut event) => { + match event.new_blocks.last() { + Some(tip) => ( + tip.block.block_identifier.clone(), + &mut event.confirmed_blocks, + ), + None => return, + } + } + StacksChainEvent::ChainUpdatedWithReorg(ref mut event) => { + match event.blocks_to_apply.last() { + Some(tip) => ( + tip.block.block_identifier.clone(), + &mut event.confirmed_blocks, + ), + None => return, + } + } + _ => return, + }; + + let mut forks_to_prune = vec![]; + let mut ancestor_identifier = &tip; + + // Retrieve the whole canonical segment present in memory, descending order + // [7] ... [2] [1] + let canonical_segment = { + let mut segment = vec![]; + while let Some(ancestor) = self.block_store.get(&ancestor_identifier) { + ancestor_identifier = &ancestor.parent_block_identifier; + segment.push(ancestor.block_identifier.clone()); + } + segment + }; + + if canonical_segment.len() < 7 { + ctx.try_log(|logger| slog::info!(logger, "No block to confirm")); + return; + } + // Any block beyond 6th ancestor is considered as confirmed and can be pruned + let cut_off = &canonical_segment[5]; + + // Prune forks using the confirmed block + let mut blocks_to_prune = vec![]; + for (fork_id, fork) in self.forks.iter_mut() { + let mut res = fork.prune_confirmed_blocks(&cut_off); + blocks_to_prune.append(&mut res); + if fork.block_ids.is_empty() { + forks_to_prune.push(*fork_id); + } + } + + // Prune orphans using the confirmed block + let iter = self.orphans.clone().into_iter(); + for orphan in iter { + if orphan.index < cut_off.index { + self.orphans.remove(&orphan); + blocks_to_prune.push(orphan); + } + } + + // Looping a first time, to collect: + // 1) the blocks that we will be returning + // 2) the tip of the trail confirmed by the subsequent block + // Block 6 (index 5) is confirming transactions included in microblocks + // that must be merged in Block 7. + let mut blocks_to_confirm = canonical_segment[6..].to_vec(); + blocks_to_confirm.reverse(); + for confirmed_block in blocks_to_confirm.iter() { + let block = match self.block_store.remove(confirmed_block) { + None => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to retrieve data for {}", confirmed_block) + }); + return; + } + Some(block) => block, + }; + confirmed_blocks.push(block); + } + + // for mut block in blocks.into_iter() { + // println!("Zip {} {:?}", block.get_identifier(), trail); + // if let Some(trail_tip) = trail { + // // The subsequent block was confirming a trail of microblock + // let canonical_micro_fork_id = + // match self.canonical_micro_fork_id.remove(&block.block_identifier) { + // None => { + // println!( + // "unable to retrieve canonical_micro_fork_id for {}", + // block.block_identifier + // ); + // return; + // } + // Some(id) => id, + // }; + // let mut segment = match self.micro_forks.remove(&block.block_identifier) { + // None => { + // println!( + // "unable to retrieve canonical_micro_fork_id for {}", + // block.block_identifier + // ); + // return; + // } + // Some(mut microforks) => microforks.remove(canonical_micro_fork_id), + // }; + // // Sanity check + // let tip = match segment.block_ids.pop_front() { + // None => { + // println!("canonical micro fork empty {}", block.block_identifier); + // return; + // } + // Some(id) => id, + // }; + // if !tip.eq(&trail_tip) { + // println!( + // "canonical micro fork mismatch for {}", + // block.block_identifier + // ); + // return; + // } + // // Replace the tip + // segment.block_ids.push_front(tip); + // while let Some(entry) = segment.block_ids.pop_back() { + // let mut microblock = match self + // .microblock_store + // .remove(&(block.block_identifier.clone(), entry.clone())) + // { + // None => { + // println!("unable to retrieve microblock data for {}", entry); + // return; + // } + // Some(microblock) => microblock, + // }; + // block.transactions.append(&mut microblock.transactions); + // } + // } + // confirmed_blocks.push(block); + // } + + // Prune data + for block_to_prune in blocks_to_prune { + self.block_store.remove(&block_to_prune); + self.micro_forks.remove(&block_to_prune); + self.canonical_micro_fork_id.remove(&block_to_prune); + // TODO(lgalabru): cascade pruning down to micro_orphans and microblocks_store + } + for fork_id in forks_to_prune { + self.forks.remove(&fork_id); + } + // confirmed_blocks.reverse(); + + ctx.try_log(|logger| slog::debug!(logger, "AFTER: {:?}", confirmed_blocks.len())); + } + + pub fn process_microblocks( + &mut self, + microblocks: Vec, + ctx: &Context, + ) -> Result, String> { + ctx.try_log(|logger| { + slog::info!(logger, "Start processing {} microblocks", microblocks.len()) + }); + + let mut previous_canonical_micro_fork = None; + + let mut micro_forks_updated = HashSet::new(); + + let mut anchor_block_updated = None; + + for mut microblock in microblocks.into_iter() { + // Temporary patch: the event observer is not returning the block height of the anchor block, + // we're using the local state to retrieve this missing piece of data. + if let Some(block) = self + .block_store + .get(µblock.metadata.anchor_block_identifier) + { + anchor_block_updated = Some(block.block_identifier.clone()); + microblock.metadata.anchor_block_identifier = block.block_identifier.clone(); + } + ctx.try_log(|logger| { + slog::info!( + logger, + "Processing microblock {}, extending anchor {}", + microblock.block_identifier, + microblock.metadata.anchor_block_identifier + ) + }); + + // Keep microblock data in memory + self.microblock_store.insert( + ( + microblock.metadata.anchor_block_identifier.clone(), + microblock.block_identifier.clone(), + ), + microblock.clone(), + ); + + if let (Some(microforks), Some(micro_fork_id)) = ( + self.micro_forks + .get(µblock.metadata.anchor_block_identifier), + self.canonical_micro_fork_id + .get(µblock.metadata.anchor_block_identifier), + ) { + ctx.try_log(|logger| { + slog::info!( + logger, + "Previous fork selected as canonical: {}", + microforks[*micro_fork_id] + ) + }); + previous_canonical_micro_fork = Some(microforks[*micro_fork_id].clone()); + } + + let mut micro_fork_updated = None; + + if microblock.block_identifier.index == 0 { + ctx.try_log(|logger| { + slog::info!( + logger, + "Initiating new micro fork {}", + microblock.block_identifier + ) + }); + let mut microfork = ChainSegment::new(); + microfork.append_block_identifier(&µblock.block_identifier); + + match self + .micro_forks + .entry(microblock.metadata.anchor_block_identifier.clone()) + { + Entry::Occupied(microforks) => microforks.into_mut().push(microfork), + Entry::Vacant(v) => { + v.insert(vec![microfork]); + } + }; + micro_fork_updated = self + .micro_forks + .get_mut(µblock.metadata.anchor_block_identifier) + .and_then(|microfork| microfork.last_mut()) + } else { + if let Some(microforks) = self + .micro_forks + .get_mut(µblock.metadata.anchor_block_identifier) + { + for micro_fork in microforks.iter_mut() { + let (block_appended, mut new_micro_fork) = + micro_fork.try_append_block(µblock, ctx); + if block_appended { + ctx.try_log(|logger| { + slog::info!(logger, + "Attempt to append micro fork {} with {} (parent = {}) succeeded", + micro_fork, + microblock.block_identifier, + microblock.parent_block_identifier + ) + }); + if let Some(new_micro_fork) = new_micro_fork.take() { + microforks.push(new_micro_fork); + micro_fork_updated = microforks.last_mut(); + } else { + micro_fork_updated = Some(micro_fork); + } + // A block can only be added to one segment + break; + } else { + ctx.try_log(|logger| { + slog::error!( + logger, + "Attempt to append micro fork {} with {} (parent = {}) failed", + micro_fork, + microblock.block_identifier, + microblock.parent_block_identifier + ) + }); + } + } + } + } + + let micro_fork_updated = match micro_fork_updated.take() { + Some(micro_fork) => micro_fork, + None => { + self.micro_orphans.insert(( + microblock.metadata.anchor_block_identifier.clone(), + microblock.block_identifier.clone(), + )); + continue; + } + }; + + // Process former orphans + let orphans = self.micro_orphans.clone(); + let mut orphans_to_untrack = HashSet::new(); + + let mut at_least_one_orphan_appended = true; + // As long as we are successful appending blocks that were previously unprocessable, + // Keep looping on this backlog + let mut applied = HashSet::new(); + while at_least_one_orphan_appended { + at_least_one_orphan_appended = false; + for orphan_key in orphans.iter() { + if applied.contains(orphan_key) { + continue; + } + let block = match self.microblock_store.get(orphan_key) { + Some(block) => block.clone(), + None => continue, + }; + + let (orphan_appended, _new_fork) = + micro_fork_updated.try_append_block(&block, ctx); + if orphan_appended { + applied.insert(orphan_key); + orphans_to_untrack.insert(orphan_key); + } + at_least_one_orphan_appended = at_least_one_orphan_appended || orphan_appended; + } + } + + // Update orphans + for orphan in orphans_to_untrack.into_iter() { + ctx.try_log(|logger| { + slog::info!( + logger, + "Dequeuing orphaned microblock ({}, {})", + orphan.0, + orphan.1 + ) + }); + self.micro_orphans.remove(orphan); + } + + micro_forks_updated.insert(microblock.metadata.anchor_block_identifier); + } + + if micro_forks_updated.is_empty() { + ctx.try_log(|logger| { + slog::info!(logger, "Unable to process microblocks - inboxed for later") + }); + return Ok(None); + } else { + ctx.try_log(|logger| slog::info!(logger, "Microblocks successfully appended")); + } + + let anchor_block_updated = match anchor_block_updated { + Some(anchor_block_updated) => anchor_block_updated, + None => { + ctx.try_log(|logger| { + slog::info!(logger, "Microblock was received before its anchorblock") + }); + return Ok(None); + } + }; + + assert_eq!(micro_forks_updated.len(), 1); + let microforks = { + let microforks = self + .micro_forks + .get(&anchor_block_updated) + .expect("unable to retrieve microforks"); + microforks + }; + + // Select canonical fork + let mut canonical_micro_fork_id = 0; + let mut highest_height = 0; + for (fork_id, fork) in microforks.iter().enumerate() { + ctx.try_log(|logger| slog::info!(logger, "Active microfork: {} - {}", fork_id, fork)); + if fork.get_length() >= highest_height { + highest_height = fork.get_length(); + canonical_micro_fork_id = fork_id; + } + } + + self.canonical_micro_fork_id + .insert(anchor_block_updated.clone(), canonical_micro_fork_id); + + // Generate chain event from the previous and current canonical forks + let canonical_micro_fork = microforks.get(canonical_micro_fork_id).unwrap(); + + ctx.try_log(|logger| { + slog::info!( + logger, + "Active microfork selected as canonical: {}", + canonical_micro_fork + ) + }); + + let chain_event = self.generate_microblock_chain_event( + &anchor_block_updated, + canonical_micro_fork, + &previous_canonical_micro_fork, + ctx, + ); + + Ok(chain_event) + } + + // We got the confirmed canonical microblock trail, + // and we want to send a diff with whatever was sent + // in the past. + // The issue comes from the following case. If we + // condider the 3 following forks + // + // 1) A1 - B1 - a1 - b1 - c1 - C1 + // + // 2) A1 - B1 - a1 - b1 - C2 + // + // 3) A1 - B1 - a1 - b1 - c1 - d1 - C3 + // + // How can we always be sending back the right diff? + // As is, if 1) 2) 3), we will be sending: + // - BlockUpdate(C1) + // - BlockReorg(C2, rollback: [c1], apply: []) + // - BlockReorg(C3, rollback: [], apply: [c1, d1]) + + pub fn confirm_microblocks_for_block( + &mut self, + block: &StacksBlockData, + diff_enabled: bool, + ctx: &Context, + ) -> (Option, Option>) { + match ( + &block.metadata.confirm_microblock_identifier, + self.micro_forks.get(&block.parent_block_identifier), + ) { + (Some(last_microblock), Some(microforks)) => { + let previous_canonical_segment = match self + .canonical_micro_fork_id + .get(&block.parent_block_identifier) + { + Some(id) => Some(microforks[*id].clone()), + None => None, + }; + + let mut new_canonical_segment = None; + for (microfork_id, microfork) in microforks.iter().enumerate() { + self.canonical_micro_fork_id + .insert(block.parent_block_identifier.clone(), microfork_id); + if microfork.block_ids.contains(&last_microblock) { + let mut confirmed_microblocks = microfork.clone(); + let (_, mutated) = confirmed_microblocks + .keep_blocks_from_oldest_to_block_identifier(&last_microblock); + new_canonical_segment = Some(( + confirmed_microblocks, + if mutated { + microforks.len() + } else { + microfork_id + }, + )); + break; + } + } + + if let Some((new_canonical_segment, microfork_id)) = new_canonical_segment { + let result = if diff_enabled { + let chain_event = self.generate_microblock_chain_event( + &block.parent_block_identifier, + &new_canonical_segment, + &previous_canonical_segment, + ctx, + ); + (chain_event, None) + } else { + ( + None, + Some(self.get_microblocks_data( + &block.parent_block_identifier, + &new_canonical_segment, + )), + ) + }; + // insert confirmed_microblocks in self.micro_forks + self.canonical_micro_fork_id + .insert(block.parent_block_identifier.clone(), microfork_id); + + // update self.canonical_micro_fork_id + match self + .micro_forks + .entry(block.parent_block_identifier.clone()) + { + Entry::Occupied(microforks) => { + microforks.into_mut().push(new_canonical_segment) + } + Entry::Vacant(v) => { + v.insert(vec![new_canonical_segment]); + } + }; + return result; + } + (None, None) + } + _ => (None, None), + } + } + + pub fn get_microblocks_data( + &self, + anchor_block_identifier: &BlockIdentifier, + chain_segment: &ChainSegment, + ) -> Vec { + let mut microblocks = vec![]; + for i in 0..chain_segment.block_ids.len() { + let block_identifier = &chain_segment.block_ids[chain_segment.block_ids.len() - 1 - i]; + let microblock_identifier = (anchor_block_identifier.clone(), block_identifier.clone()); + let block = match self.microblock_store.get(µblock_identifier) { + Some(block) => block.clone(), + None => panic!("unable to retrive microblock from microblock store"), + }; + microblocks.push(block) + } + microblocks + } + + pub fn get_confirmed_parent_microblocks( + &self, + block: &StacksBlockData, + ) -> Vec { + match self.micro_forks.get(&block.parent_block_identifier) { + Some(microforks) => { + let previous_canonical_segment = match self + .canonical_micro_fork_id + .get(&block.parent_block_identifier) + { + Some(id) => { + self.get_microblocks_data(&block.parent_block_identifier, µforks[*id]) + } + None => vec![], + }; + previous_canonical_segment + } + _ => vec![], + } + } + + pub fn generate_block_chain_event( + &mut self, + canonical_segment: &ChainSegment, + other_segment: &ChainSegment, + ctx: &Context, + ) -> Result { + if other_segment.is_empty() { + let mut new_blocks = vec![]; + for i in 0..canonical_segment.block_ids.len() { + let block_identifier = + &canonical_segment.block_ids[canonical_segment.block_ids.len() - 1 - i]; + let block = match self.block_store.get(block_identifier) { + Some(block) => block.clone(), + None => { + ctx.try_log(|logger| { + slog::error!( + logger, + "unable to retrieve Stacks {} from block store", + block_identifier + ) + }); + return Err(ChainSegmentIncompatibility::Unknown); + } + }; + let block_update = match self.confirm_microblocks_for_block(&block, true, ctx) { + (Some(ref mut chain_event), _) => { + let mut update = StacksBlockUpdate::new(block); + match chain_event { + StacksChainEvent::ChainUpdatedWithMicroblocks(data) => { + update + .parent_microblocks_to_apply + .append(&mut data.new_microblocks); + } + StacksChainEvent::ChainUpdatedWithMicroblocksReorg(data) => { + update + .parent_microblocks_to_apply + .append(&mut data.microblocks_to_apply); + update + .parent_microblocks_to_rollback + .append(&mut data.microblocks_to_rollback); + } + _ => unreachable!(), + }; + update + } + _ => StacksBlockUpdate::new(block), + }; + new_blocks.push(block_update) + } + return Ok(StacksChainEvent::ChainUpdatedWithBlocks( + StacksChainUpdatedWithBlocksData { + new_blocks, + confirmed_blocks: vec![], + }, + )); + } + if let Ok(divergence) = canonical_segment.try_identify_divergence(other_segment, false, ctx) + { + if divergence.blocks_to_rollback.is_empty() { + let mut new_blocks = vec![]; + for i in 0..divergence.blocks_to_apply.len() { + let block_identifier = &divergence.blocks_to_apply[i]; + let block = match self.block_store.get(block_identifier) { + Some(block) => block.clone(), + None => panic!("unable to retrive block from block store"), + }; + let block_update = match self.confirm_microblocks_for_block(&block, true, ctx) { + (Some(ref mut chain_event), None) => { + let mut update = StacksBlockUpdate::new(block); + match chain_event { + StacksChainEvent::ChainUpdatedWithMicroblocks(data) => { + update + .parent_microblocks_to_apply + .append(&mut data.new_microblocks); + } + StacksChainEvent::ChainUpdatedWithMicroblocksReorg(data) => { + update + .parent_microblocks_to_apply + .append(&mut data.microblocks_to_apply); + update + .parent_microblocks_to_rollback + .append(&mut data.microblocks_to_rollback); + } + _ => unreachable!(), + }; + update + } + _ => StacksBlockUpdate::new(block), + }; + new_blocks.push(block_update) + } + return Ok(StacksChainEvent::ChainUpdatedWithBlocks( + StacksChainUpdatedWithBlocksData { + new_blocks, + confirmed_blocks: vec![], + }, + )); + } else { + return Ok(StacksChainEvent::ChainUpdatedWithReorg( + StacksChainUpdatedWithReorgData { + blocks_to_rollback: divergence + .blocks_to_rollback + .iter() + .map(|block_id| { + let block = match self.block_store.get(block_id) { + Some(block) => block.clone(), + None => panic!("unable to retrive block from block store"), + }; + let parent_microblocks_to_rollback = + self.get_confirmed_parent_microblocks(&block); + let mut update = StacksBlockUpdate::new(block); + update.parent_microblocks_to_rollback = + parent_microblocks_to_rollback; + update + }) + .collect::>(), + blocks_to_apply: divergence + .blocks_to_apply + .iter() + .map(|block_id| { + let block = match self.block_store.get(block_id) { + Some(block) => block.clone(), + None => panic!("unable to retrive block from block store"), + }; + let block_update = match self + .confirm_microblocks_for_block(&block, false, ctx) + { + (_, Some(microblocks_to_apply)) => { + let mut update = StacksBlockUpdate::new(block); + update.parent_microblocks_to_apply = microblocks_to_apply; + update + } + _ => StacksBlockUpdate::new(block), + }; + block_update + }) + .collect::>(), + confirmed_blocks: vec![], + }, + )); + } + } + ctx.try_log(|logger| { + slog::warn!( + logger, + "Unable to infer chain event out of {} and {}", + canonical_segment, + other_segment + ) + }); + Err(ChainSegmentIncompatibility::ParentBlockUnknown) + } + + pub fn generate_microblock_chain_event( + &self, + anchor_block_identifier: &BlockIdentifier, + new_canonical_segment: &ChainSegment, + previous_canonical_segment: &Option, + ctx: &Context, + ) -> Option { + let previous_canonical_segment = match previous_canonical_segment { + Some(previous_canonical_segment) if !previous_canonical_segment.is_empty() => { + previous_canonical_segment + } + _ => { + let mut new_microblocks = vec![]; + for i in 0..new_canonical_segment.block_ids.len() { + let block_identifier = &new_canonical_segment.block_ids + [new_canonical_segment.block_ids.len() - 1 - i]; + let microblock_identifier = + (anchor_block_identifier.clone(), block_identifier.clone()); + let block = match self.microblock_store.get(µblock_identifier) { + Some(block) => block.clone(), + None => panic!("unable to retrive microblock from microblock store"), + }; + new_microblocks.push(block) + } + return Some(StacksChainEvent::ChainUpdatedWithMicroblocks( + StacksChainUpdatedWithMicroblocksData { new_microblocks }, + )); + } + }; + + if new_canonical_segment.eq(&previous_canonical_segment) { + return None; + } + + if let Ok(divergence) = + new_canonical_segment.try_identify_divergence(previous_canonical_segment, true, ctx) + { + if divergence.blocks_to_rollback.is_empty() { + let mut new_microblocks = vec![]; + for i in 0..divergence.blocks_to_apply.len() { + let block_identifier = &new_canonical_segment.block_ids[i]; + + let microblock_identifier = + (anchor_block_identifier.clone(), block_identifier.clone()); + let block = match self.microblock_store.get(µblock_identifier) { + Some(block) => block.clone(), + None => { + panic!("unable to retrive microblock from microblock store") + } + }; + new_microblocks.push(block); + } + return Some(StacksChainEvent::ChainUpdatedWithMicroblocks( + StacksChainUpdatedWithMicroblocksData { new_microblocks }, + )); + } else { + return Some(StacksChainEvent::ChainUpdatedWithMicroblocksReorg( + StacksChainUpdatedWithMicroblocksReorgData { + microblocks_to_rollback: divergence + .blocks_to_rollback + .iter() + .map(|microblock_identifier| { + let microblock_identifier = ( + anchor_block_identifier.clone(), + microblock_identifier.clone(), + ); + let block = match self.microblock_store.get(µblock_identifier) + { + Some(block) => block.clone(), + None => { + panic!("unable to retrive microblock from microblock store") + } + }; + block + }) + .collect::>(), + microblocks_to_apply: divergence + .blocks_to_apply + .iter() + .map(|microblock_identifier| { + let microblock_identifier = ( + anchor_block_identifier.clone(), + microblock_identifier.clone(), + ); + let block = match self.microblock_store.get(µblock_identifier) + { + Some(block) => block.clone(), + None => { + panic!("unable to retrive microblock from microblock store") + } + }; + block + }) + .collect::>(), + }, + )); + } + } + None + } +} diff --git a/components/chainhook-event-observer/src/indexer/stacks/mod.rs b/components/chainhook-event-observer/src/indexer/stacks/mod.rs new file mode 100644 index 0000000..b590641 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/stacks/mod.rs @@ -0,0 +1,1094 @@ +mod blocks_pool; + +pub use blocks_pool::StacksBlockPool; + +use crate::indexer::AssetClassCache; +use crate::indexer::{IndexerConfig, StacksChainContext}; +use crate::utils::Context; +use chainhook_types::*; +use clarity_repl::clarity::codec::StacksMessageCodec; +use clarity_repl::clarity::util::hash::hex_bytes; +use clarity_repl::clarity::vm::types::Value as ClarityValue; +use clarity_repl::codec::{StacksTransaction, TransactionAuth, TransactionPayload}; +use hiro_system_kit::slog; +use rocket::serde::json::Value as JsonValue; +use rocket::serde::Deserialize; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::convert::TryInto; +use std::io::Cursor; +use std::str; + +#[derive(Deserialize)] +pub struct NewBlock { + pub block_height: u64, + pub block_hash: String, + pub index_block_hash: String, + pub burn_block_height: u64, + pub burn_block_hash: String, + pub parent_block_hash: String, + pub parent_index_block_hash: String, + pub parent_microblock: String, + pub parent_microblock_sequence: u64, + pub parent_burn_block_hash: String, + pub parent_burn_block_height: u64, + pub parent_burn_block_timestamp: i64, + pub transactions: Vec, + pub events: Vec, + pub matured_miner_rewards: Vec, +} + +#[derive(Deserialize, Serialize, Default, Clone)] +pub struct NewBlockHeader { + pub block_height: u64, + pub index_block_hash: Option, + pub parent_index_block_hash: Option, +} + +#[derive(Deserialize)] +pub struct MaturedMinerReward { + pub from_index_consensus_hash: String, + pub from_stacks_block_hash: String, + pub recipient: String, + pub coinbase_amount: String, + /// micro-STX amount + pub tx_fees_anchored: String, + /// micro-STX amount + pub tx_fees_streamed_confirmed: String, + /// micro-STX amount + pub tx_fees_streamed_produced: String, +} + +#[derive(Deserialize, Debug)] +pub struct NewMicroblockTrail { + pub parent_index_block_hash: String, + pub burn_block_hash: String, + pub burn_block_height: u64, + pub burn_block_timestamp: i64, + pub transactions: Vec, + pub events: Vec, +} + +#[derive(Deserialize, Debug)] +pub struct NewTransaction { + pub txid: String, + pub tx_index: usize, + pub status: String, + pub raw_result: String, + pub raw_tx: String, + pub execution_cost: Option, +} + +#[derive(Deserialize, Debug)] +pub struct NewMicroblockTransaction { + pub txid: String, + pub tx_index: usize, + pub status: String, + pub raw_result: String, + pub raw_tx: String, + pub execution_cost: Option, + pub microblock_sequence: usize, + pub microblock_hash: String, + pub microblock_parent_hash: String, +} + +#[derive(Debug, Deserialize)] +pub struct NewEvent { + pub txid: String, + pub committed: bool, + pub event_index: u32, + #[serde(rename = "type")] + pub event_type: String, + pub stx_transfer_event: Option, + pub stx_mint_event: Option, + pub stx_burn_event: Option, + pub stx_lock_event: Option, + pub nft_transfer_event: Option, + pub nft_mint_event: Option, + pub nft_burn_event: Option, + pub ft_transfer_event: Option, + pub ft_mint_event: Option, + pub ft_burn_event: Option, + pub data_var_set_event: Option, + pub data_map_insert_event: Option, + pub data_map_update_event: Option, + pub data_map_delete_event: Option, + pub contract_event: Option, +} + +impl NewEvent { + pub fn into_chainhook_event(&self) -> Result { + if let Some(ref event_data) = self.stx_mint_event { + let data: STXMintEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::STXMintEvent(data.clone())); + } else if let Some(ref event_data) = self.stx_lock_event { + let data: STXLockEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::STXLockEvent(data.clone())); + } else if let Some(ref event_data) = self.stx_burn_event { + let data: STXBurnEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::STXBurnEvent(data.clone())); + } else if let Some(ref event_data) = self.stx_transfer_event { + let data: STXTransferEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::STXTransferEvent(data.clone())); + } else if let Some(ref event_data) = self.nft_mint_event { + let data: NFTMintEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::NFTMintEvent(data.clone())); + } else if let Some(ref event_data) = self.nft_burn_event { + let data: NFTBurnEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::NFTBurnEvent(data.clone())); + } else if let Some(ref event_data) = self.nft_transfer_event { + let data: NFTTransferEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::NFTTransferEvent(data.clone())); + } else if let Some(ref event_data) = self.ft_mint_event { + let data: FTMintEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::FTMintEvent(data.clone())); + } else if let Some(ref event_data) = self.ft_burn_event { + let data: FTBurnEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::FTBurnEvent(data.clone())); + } else if let Some(ref event_data) = self.ft_transfer_event { + let data: FTTransferEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::FTTransferEvent(data.clone())); + } else if let Some(ref event_data) = self.data_var_set_event { + let data: DataVarSetEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::DataVarSetEvent(data.clone())); + } else if let Some(ref event_data) = self.data_map_insert_event { + let data: DataMapInsertEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::DataMapInsertEvent(data.clone())); + } else if let Some(ref event_data) = self.data_map_update_event { + let data: DataMapUpdateEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::DataMapUpdateEvent(data.clone())); + } else if let Some(ref event_data) = self.data_map_delete_event { + let data: DataMapDeleteEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::DataMapDeleteEvent(data.clone())); + } else if let Some(ref event_data) = self.contract_event { + let data: SmartContractEventData = + serde_json::from_value(event_data.clone()).expect("Unable to decode event_data"); + return Ok(StacksTransactionEvent::SmartContractEvent(data.clone())); + } + return Err(format!("unable to support event type")); + } +} + +pub fn get_stacks_currency() -> Currency { + Currency { + symbol: "STX".into(), + decimals: 6, + metadata: None, + } +} + +#[derive(Deserialize, Debug)] +pub struct ContractReadonlyCall { + pub okay: bool, + pub result: String, +} + +pub fn standardize_stacks_serialized_block_header( + serialized_block: &str, +) -> Result<(BlockIdentifier, BlockIdentifier), String> { + let mut block_header: NewBlockHeader = serde_json::from_str(serialized_block) + .map_err(|e| format!("unable to parse stacks block_header {}", e.to_string()))?; + let hash = block_header + .index_block_hash + .take() + .ok_or(format!("unable to retrieve index_block_hash"))?; + let block_identifier = BlockIdentifier { + hash, + index: block_header.block_height, + }; + let parent_hash = block_header + .parent_index_block_hash + .take() + .ok_or(format!("unable to retrieve parent_index_block_hash"))?; + let parent_block_identifier = BlockIdentifier { + hash: parent_hash, + index: block_identifier.index - 1, + }; + Ok((block_identifier, parent_block_identifier)) +} + +pub fn standardize_stacks_serialized_block( + indexer_config: &IndexerConfig, + serialized_block: &str, + chain_ctx: &mut StacksChainContext, + ctx: &Context, +) -> Result { + let mut block: NewBlock = serde_json::from_str(serialized_block) + .map_err(|e| format!("unable to parse stacks block_header {}", e.to_string()))?; + standardize_stacks_block(indexer_config, &mut block, chain_ctx, ctx) +} + +pub fn standardize_stacks_marshalled_block( + indexer_config: &IndexerConfig, + marshalled_block: JsonValue, + chain_ctx: &mut StacksChainContext, + ctx: &Context, +) -> Result { + let mut block: NewBlock = serde_json::from_value(marshalled_block) + .map_err(|e| format!("unable to parse stacks block {}", e.to_string()))?; + standardize_stacks_block(indexer_config, &mut block, chain_ctx, ctx) +} + +pub fn standardize_stacks_block( + indexer_config: &IndexerConfig, + block: &mut NewBlock, + chain_ctx: &mut StacksChainContext, + ctx: &Context, +) -> Result { + let pox_cycle_length: u64 = (chain_ctx.pox_info.prepare_phase_block_length + + chain_ctx.pox_info.reward_phase_block_length) + .into(); + let current_len = + block.burn_block_height - (1 + chain_ctx.pox_info.first_burnchain_block_height); + let pox_cycle_id: u32 = (current_len / pox_cycle_length).try_into().unwrap_or(0); + let mut events: HashMap<&String, Vec<&NewEvent>> = HashMap::new(); + for event in block.events.iter() { + events + .entry(&event.txid) + .and_modify(|events| events.push(&event)) + .or_insert(vec![&event]); + } + + let mut transactions = vec![]; + for tx in block.transactions.iter() { + let tx_events = events.remove(&tx.txid).unwrap_or(vec![]); + let (description, tx_type, fee, nonce, sender, sponsor) = + match get_tx_description(&tx.raw_tx, &tx_events) { + Ok(desc) => desc, + Err(e) => { + return Err(format!("unable to standardize block ({})", e.to_string())); + } + }; + let events = tx_events + .iter() + .map(|e| e.into_chainhook_event()) + .collect::, String>>()?; + let (receipt, operations) = get_standardized_stacks_receipt( + &tx.txid, + events, + &mut chain_ctx.asset_class_map, + &indexer_config.stacks_node_rpc_url, + true, + ); + + transactions.push(StacksTransactionData { + transaction_identifier: TransactionIdentifier { + hash: tx.txid.clone(), + }, + operations, + metadata: StacksTransactionMetadata { + success: tx.status == "success", + result: get_value_description(&tx.raw_result, ctx), + raw_tx: tx.raw_tx.clone(), + sender, + nonce, + fee, + sponsor, + kind: tx_type, + execution_cost: tx.execution_cost.clone(), + receipt, + description, + position: StacksTransactionPosition::anchor_block(tx.tx_index), + proof: None, + }, + }); + } + + let confirm_microblock_identifier = if block.parent_microblock + == "0x0000000000000000000000000000000000000000000000000000000000000000" + { + None + } else { + Some(BlockIdentifier { + index: block + .parent_microblock_sequence + .try_into() + .expect("unable to get microblock sequence"), + hash: block.parent_microblock.clone(), + }) + }; + + let block = StacksBlockData { + block_identifier: BlockIdentifier { + hash: block.index_block_hash.clone(), + index: block.block_height, + }, + parent_block_identifier: BlockIdentifier { + hash: block.parent_index_block_hash.clone(), + index: block.block_height - 1, + }, + timestamp: block.parent_burn_block_timestamp, + metadata: StacksBlockMetadata { + bitcoin_anchor_block_identifier: BlockIdentifier { + hash: block.burn_block_hash.clone(), + index: block.burn_block_height, + }, + pox_cycle_index: pox_cycle_id, + pox_cycle_position: (current_len % pox_cycle_length) as u32, + pox_cycle_length: pox_cycle_length.try_into().unwrap(), + confirm_microblock_identifier, + }, + transactions, + }; + Ok(block) +} + +pub fn standardize_stacks_serialized_microblock_trail( + indexer_config: &IndexerConfig, + serialized_microblock_trail: &str, + chain_ctx: &mut StacksChainContext, + ctx: &Context, +) -> Result, String> { + let mut microblock_trail: NewMicroblockTrail = + serde_json::from_str(serialized_microblock_trail) + .map_err(|e| format!("unable to parse microblock trail {}", e.to_string()))?; + standardize_stacks_microblock_trail(indexer_config, &mut microblock_trail, chain_ctx, ctx) +} + +pub fn standardize_stacks_marshalled_microblock_trail( + indexer_config: &IndexerConfig, + marshalled_microblock_trail: JsonValue, + chain_ctx: &mut StacksChainContext, + ctx: &Context, +) -> Result, String> { + let mut microblock_trail: NewMicroblockTrail = + serde_json::from_value(marshalled_microblock_trail) + .map_err(|e| format!("unable to parse microblock trail {}", e.to_string()))?; + standardize_stacks_microblock_trail(indexer_config, &mut microblock_trail, chain_ctx, ctx) +} + +pub fn standardize_stacks_microblock_trail( + indexer_config: &IndexerConfig, + microblock_trail: &mut NewMicroblockTrail, + chain_ctx: &mut StacksChainContext, + ctx: &Context, +) -> Result, String> { + let mut events: HashMap<&String, Vec<&NewEvent>> = HashMap::new(); + for event in microblock_trail.events.iter() { + events + .entry(&event.txid) + .and_modify(|events| events.push(&event)) + .or_insert(vec![&event]); + } + let mut microblocks_set: BTreeMap< + (BlockIdentifier, BlockIdentifier), + Vec, + > = BTreeMap::new(); + for tx in microblock_trail.transactions.iter() { + let tx_events = events.remove(&tx.txid).unwrap_or(vec![]); + let (description, tx_type, fee, nonce, sender, sponsor) = + get_tx_description(&tx.raw_tx, &tx_events).expect("unable to parse transaction"); + + let events = tx_events + .iter() + .map(|e| e.into_chainhook_event()) + .collect::, String>>()?; + let (receipt, operations) = get_standardized_stacks_receipt( + &tx.txid, + events, + &mut chain_ctx.asset_class_map, + &indexer_config.stacks_node_rpc_url, + true, + ); + + let microblock_identifier = BlockIdentifier { + hash: tx.microblock_hash.clone(), + index: u64::try_from(tx.microblock_sequence).unwrap(), + }; + + let parent_microblock_identifier = if tx.microblock_sequence > 0 { + BlockIdentifier { + hash: tx.microblock_parent_hash.clone(), + index: microblock_identifier.index.saturating_sub(1), + } + } else { + microblock_identifier.clone() + }; + + let transaction = StacksTransactionData { + transaction_identifier: TransactionIdentifier { + hash: tx.txid.clone(), + }, + operations, + metadata: StacksTransactionMetadata { + success: tx.status == "success", + result: get_value_description(&tx.raw_result, ctx), + raw_tx: tx.raw_tx.clone(), + sender, + fee, + nonce, + sponsor, + kind: tx_type, + execution_cost: tx.execution_cost.clone(), + receipt, + description, + position: StacksTransactionPosition::micro_block( + microblock_identifier.clone(), + tx.tx_index, + ), + proof: None, + }, + }; + + microblocks_set + .entry((microblock_identifier, parent_microblock_identifier)) + .and_modify(|transactions| transactions.push(transaction.clone())) + .or_insert(vec![transaction]); + } + + let mut microblocks = vec![]; + for ((block_identifier, parent_block_identifier), transactions) in microblocks_set.into_iter() { + microblocks.push(StacksMicroblockData { + block_identifier, + parent_block_identifier, + timestamp: microblock_trail.burn_block_timestamp, + transactions, + metadata: StacksMicroblockMetadata { + anchor_block_identifier: BlockIdentifier { + hash: microblock_trail.parent_index_block_hash.clone(), + index: 0, + }, + }, + }) + } + microblocks.sort_by(|a, b| b.block_identifier.cmp(&a.block_identifier)); + + Ok(microblocks) +} + +pub fn get_value_description(raw_value: &str, ctx: &Context) -> String { + let raw_value = match raw_value.strip_prefix("0x") { + Some(raw_value) => raw_value, + _ => return raw_value.to_string(), + }; + let value_bytes = match hex_bytes(&raw_value) { + Ok(bytes) => bytes, + _ => return raw_value.to_string(), + }; + + let value = match ClarityValue::consensus_deserialize(&mut Cursor::new(&value_bytes)) { + Ok(value) => format!("{}", value), + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to deserialize clarity value {:?}", e) + }); + return raw_value.to_string(); + } + }; + value +} + +pub fn get_tx_description( + raw_tx: &str, + tx_events: &Vec<&NewEvent>, +) -> Result< + ( + String, // Human readable transaction's description (contract-call, publish, ...) + StacksTransactionKind, // Transaction kind + u64, // Transaction fee + u64, // Transaction nonce + String, // Sender's address + Option, // Sponsor's address (optional) + ), + String, +> { + let raw_tx = match raw_tx.strip_prefix("0x") { + Some(raw_tx) => raw_tx, + _ => return Err("unable to read txid".into()), + }; + let tx_bytes = match hex_bytes(&raw_tx) { + Ok(bytes) => bytes, + Err(e) => return Err(format!("unable to read txid {}", e.to_string())), + }; + + // Handle Stacks transitions operated through Bitcoin transactions + if tx_bytes.eq(&[0]) { + if tx_events.is_empty() { + return Err(format!( + "received block with transaction '0x00' and no events" + )); + }; + for event in tx_events.iter() { + if let Some(ref event_data) = event.stx_transfer_event { + let data: STXTransferEventData = serde_json::from_value(event_data.clone()) + .map_err(|e| format!("unable to decode event_data {}", e.to_string()))?; + let description = format!( + "transfered: {} µSTX from {} to {} through Bitcoin transaction", + data.amount, data.sender, data.recipient + ); + let tx_type = StacksTransactionKind::NativeTokenTransfer; + return Ok((description, tx_type, 0, 0, data.sender, None)); + } else if let Some(ref event_data) = event.stx_lock_event { + let data: STXLockEventData = serde_json::from_value(event_data.clone()) + .map_err(|e| format!("unable to decode event_data {}", e.to_string()))?; + let description = format!( + "stacked: {} µSTX by {} through Bitcoin transaction", + data.locked_amount, data.locked_address, + ); + let tx_type = StacksTransactionKind::Other; + return Ok((description, tx_type, 0, 0, data.locked_address, None)); + } + } + return Err(format!( + "unable to parse transaction {raw_tx} with events {:?}", + tx_events + )); + } + + let tx = StacksTransaction::consensus_deserialize(&mut Cursor::new(&tx_bytes)) + .map_err(|e| format!("unable to consensus decode transaction {}", e.to_string()))?; + + let (fee, nonce, sender, sponsor) = match tx.auth { + TransactionAuth::Standard(ref conditions) => ( + conditions.tx_fee(), + conditions.nonce(), + if tx.is_mainnet() { + conditions.address_mainnet().to_string() + } else { + conditions.address_testnet().to_string() + }, + None, + ), + TransactionAuth::Sponsored(ref sender_conditions, ref sponsor_conditions) => ( + sponsor_conditions.tx_fee(), + sender_conditions.nonce(), + if tx.is_mainnet() { + sender_conditions.address_mainnet().to_string() + } else { + sender_conditions.address_testnet().to_string() + }, + Some(if tx.is_mainnet() { + sponsor_conditions.address_mainnet().to_string() + } else { + sponsor_conditions.address_testnet().to_string() + }), + ), + }; + + let (description, tx_type) = match tx.payload { + TransactionPayload::TokenTransfer(ref addr, ref amount, ref _memo) => ( + format!( + "transfered: {} µSTX from {} to {}", + amount, + tx.origin_address(), + addr + ), + StacksTransactionKind::NativeTokenTransfer, + ), + TransactionPayload::ContractCall(ref contract_call) => { + let formatted_args = contract_call + .function_args + .iter() + .map(|v| format!("{}", v)) + .collect::>(); + ( + format!( + "invoked: {}.{}::{}({})", + contract_call.address, + contract_call.contract_name, + contract_call.function_name, + formatted_args.join(", ") + ), + StacksTransactionKind::ContractCall(StacksContractCallData { + contract_identifier: format!( + "{}.{}", + contract_call.address, contract_call.contract_name + ), + method: contract_call.function_name.to_string(), + args: formatted_args, + }), + ) + } + TransactionPayload::SmartContract(ref smart_contract, ref _clarity_version) => { + let contract_identifier = format!("{}.{}", tx.origin_address(), smart_contract.name); + let data = StacksContractDeploymentData { + contract_identifier: contract_identifier.clone(), + code: smart_contract.code_body.to_string(), + }; + ( + format!("deployed: {}", contract_identifier), + StacksTransactionKind::ContractDeployment(data), + ) + } + TransactionPayload::Coinbase(_, _) => { + (format!("coinbase"), StacksTransactionKind::Coinbase) + } + _ => (format!("other"), StacksTransactionKind::Other), + }; + Ok((description, tx_type, fee, nonce, sender, sponsor)) +} + +pub fn get_standardized_fungible_currency_from_asset_class_id( + asset_class_id: &str, + asset_class_cache: &mut HashMap, + _node_url: &str, +) -> Currency { + match asset_class_cache.get(asset_class_id) { + None => { + // TODO(lgalabru): re-approach this, with an adequate runtime strategy. + // let comps = asset_class_id.split("::").collect::>(); + // let principal = comps[0].split(".").collect::>(); + // let contract_address = principal[0]; + // let contract_name = principal[1]; + // let stacks_rpc = StacksRpc::new(&node_url); + // let value = stacks_rpc + // .call_read_only_fn( + // &contract_address, + // &contract_name, + // "get-symbol", + // vec![], + // contract_address, + // ) + // .expect("Unable to retrieve symbol"); + let symbol = "TOKEN".into(); //value.expect_result_ok().expect_ascii(); + + // let value = stacks_rpc + // .call_read_only_fn( + // &contract_address, + // &contract_name, + // "get-decimals", + // vec![], + // &contract_address, + // ) + // .expect("Unable to retrieve decimals"); + let decimals = 6; // value.expect_result_ok().expect_u128() as u8; + + let entry = AssetClassCache { symbol, decimals }; + + let currency = Currency { + symbol: entry.symbol.clone(), + decimals: entry.decimals.into(), + metadata: Some(CurrencyMetadata { + asset_class_identifier: asset_class_id.into(), + asset_identifier: None, + standard: CurrencyStandard::Sip10, + }), + }; + + asset_class_cache.insert(asset_class_id.into(), entry); + + currency + } + Some(entry) => Currency { + symbol: entry.symbol.clone(), + decimals: entry.decimals.into(), + metadata: Some(CurrencyMetadata { + asset_class_identifier: asset_class_id.into(), + asset_identifier: None, + standard: CurrencyStandard::Sip10, + }), + }, + } +} + +pub fn get_standardized_non_fungible_currency_from_asset_class_id( + asset_class_id: &str, + asset_id: &str, + _asset_class_cache: &mut HashMap, +) -> Currency { + Currency { + symbol: asset_class_id.into(), + decimals: 0, + metadata: Some(CurrencyMetadata { + asset_class_identifier: asset_class_id.into(), + asset_identifier: Some(asset_id.into()), + standard: CurrencyStandard::Sip09, + }), + } +} + +pub fn get_standardized_stacks_receipt( + _txid: &str, + events: Vec, + asset_class_cache: &mut HashMap, + node_url: &str, + include_operations: bool, +) -> (StacksTransactionReceipt, Vec) { + let mut mutated_contracts_radius = HashSet::new(); + let mut mutated_assets_radius = HashSet::new(); + let mut operations = vec![]; + + if include_operations { + let mut operation_id = 0; + for event in events.iter() { + match event { + StacksTransactionEvent::STXMintEvent(data) => { + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Credit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.recipient.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency: get_stacks_currency(), + }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::STXLockEvent(data) => { + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Lock, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.locked_address.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data + .locked_amount + .parse::() + .expect("Unable to parse u64"), + currency: get_stacks_currency(), + }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::STXBurnEvent(data) => { + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Debit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.sender.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency: get_stacks_currency(), + }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::STXTransferEvent(data) => { + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: Some(vec![OperationIdentifier { + index: operation_id + 1, + network_index: None, + }]), + type_: OperationType::Debit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.sender.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency: get_stacks_currency(), + }), + metadata: None, + }); + operation_id += 1; + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: Some(vec![OperationIdentifier { + index: operation_id - 1, + network_index: None, + }]), + type_: OperationType::Credit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.recipient.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency: get_stacks_currency(), + }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::NFTMintEvent(data) => { + let (asset_class_identifier, contract_identifier) = + get_mutated_ids(&data.asset_class_identifier); + mutated_assets_radius.insert(asset_class_identifier); + mutated_contracts_radius.insert(contract_identifier); + + let currency = get_standardized_non_fungible_currency_from_asset_class_id( + &data.asset_class_identifier, + &data.hex_asset_identifier, + asset_class_cache, + ); + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Credit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.recipient.clone(), + sub_account: None, + }, + amount: Some(Amount { value: 1, currency }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::NFTBurnEvent(data) => { + let (asset_class_identifier, contract_identifier) = + get_mutated_ids(&data.asset_class_identifier); + mutated_assets_radius.insert(asset_class_identifier); + mutated_contracts_radius.insert(contract_identifier); + + let currency = get_standardized_non_fungible_currency_from_asset_class_id( + &data.asset_class_identifier, + &data.hex_asset_identifier, + asset_class_cache, + ); + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Debit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.sender.clone(), + sub_account: None, + }, + amount: Some(Amount { value: 1, currency }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::NFTTransferEvent(data) => { + let (asset_class_identifier, contract_identifier) = + get_mutated_ids(&data.asset_class_identifier); + mutated_assets_radius.insert(asset_class_identifier); + mutated_contracts_radius.insert(contract_identifier); + + let currency = get_standardized_non_fungible_currency_from_asset_class_id( + &data.asset_class_identifier, + &data.hex_asset_identifier, + asset_class_cache, + ); + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: Some(vec![OperationIdentifier { + index: operation_id + 1, + network_index: None, + }]), + type_: OperationType::Debit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.sender.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: 1, + currency: currency.clone(), + }), + metadata: None, + }); + operation_id += 1; + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: Some(vec![OperationIdentifier { + index: operation_id - 1, + network_index: None, + }]), + type_: OperationType::Credit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.recipient.clone(), + sub_account: None, + }, + amount: Some(Amount { value: 1, currency }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::FTMintEvent(data) => { + let (asset_class_identifier, contract_identifier) = + get_mutated_ids(&data.asset_class_identifier); + mutated_assets_radius.insert(asset_class_identifier); + mutated_contracts_radius.insert(contract_identifier); + + let currency = get_standardized_fungible_currency_from_asset_class_id( + &data.asset_class_identifier, + asset_class_cache, + node_url, + ); + + let value = match data.amount.parse::() { + Ok(value) => value, + Err(e) => { + panic!("unable to parse u64 {:?}: {:?}", data, e); + } + }; + + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Credit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.recipient.clone(), + sub_account: None, + }, + amount: Some(Amount { value, currency }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::FTBurnEvent(data) => { + let (asset_class_identifier, contract_identifier) = + get_mutated_ids(&data.asset_class_identifier); + mutated_assets_radius.insert(asset_class_identifier); + mutated_contracts_radius.insert(contract_identifier); + + let currency = get_standardized_fungible_currency_from_asset_class_id( + &data.asset_class_identifier, + asset_class_cache, + node_url, + ); + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: None, + type_: OperationType::Debit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.sender.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency, + }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::FTTransferEvent(data) => { + let (asset_class_identifier, contract_identifier) = + get_mutated_ids(&data.asset_class_identifier); + mutated_assets_radius.insert(asset_class_identifier); + mutated_contracts_radius.insert(contract_identifier); + + let currency = get_standardized_fungible_currency_from_asset_class_id( + &data.asset_class_identifier, + asset_class_cache, + node_url, + ); + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: Some(vec![OperationIdentifier { + index: operation_id + 1, + network_index: None, + }]), + type_: OperationType::Debit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.sender.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency: currency.clone(), + }), + metadata: None, + }); + operation_id += 1; + operations.push(Operation { + operation_identifier: OperationIdentifier { + index: operation_id, + network_index: None, + }, + related_operations: Some(vec![OperationIdentifier { + index: operation_id - 1, + network_index: None, + }]), + type_: OperationType::Credit, + status: Some(OperationStatusKind::Success), + account: AccountIdentifier { + address: data.recipient.clone(), + sub_account: None, + }, + amount: Some(Amount { + value: data.amount.parse::().expect("Unable to parse u64"), + currency, + }), + metadata: None, + }); + operation_id += 1; + } + StacksTransactionEvent::DataVarSetEvent(_data) => {} + StacksTransactionEvent::DataMapInsertEvent(_data) => {} + StacksTransactionEvent::DataMapUpdateEvent(_data) => {} + StacksTransactionEvent::DataMapDeleteEvent(_data) => {} + StacksTransactionEvent::SmartContractEvent(data) => { + mutated_contracts_radius.insert(data.contract_identifier.clone()); + } + } + } + } + + let receipt = + StacksTransactionReceipt::new(mutated_contracts_radius, mutated_assets_radius, events); + (receipt, operations) +} + +fn get_mutated_ids(asset_class_id: &str) -> (String, String) { + let contract_id = asset_class_id.split("::").collect::>()[0]; + (asset_class_id.into(), contract_id.into()) +} + +#[cfg(test)] +pub mod tests; diff --git a/components/chainhook-event-observer/src/indexer/stacks/tests.rs b/components/chainhook-event-observer/src/indexer/stacks/tests.rs new file mode 100644 index 0000000..1df4b68 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/stacks/tests.rs @@ -0,0 +1,256 @@ +use super::super::tests::{helpers, process_stacks_blocks_and_check_expectations}; + +#[test] +fn test_stacks_vector_001() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_001()); +} + +#[test] +fn test_stacks_vector_002() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_002()); +} + +#[test] +fn test_stacks_vector_003() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_003()); +} + +#[test] +fn test_stacks_vector_004() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_004()); +} + +#[test] +fn test_stacks_vector_005() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_005()); +} + +#[test] +fn test_stacks_vector_006() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_006()); +} + +#[test] +fn test_stacks_vector_007() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_007()); +} + +#[test] +fn test_stacks_vector_008() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_008()); +} + +#[test] +fn test_stacks_vector_009() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_009()); +} + +#[test] +fn test_stacks_vector_010() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_010()); +} + +#[test] +fn test_stacks_vector_011() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_011()); +} + +#[test] +fn test_stacks_vector_012() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_012()); +} + +#[test] +fn test_stacks_vector_013() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_013()); +} + +#[test] +fn test_stacks_vector_014() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_014()); +} + +#[test] +fn test_stacks_vector_015() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_015()); +} + +#[test] +fn test_stacks_vector_016() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_016()); +} + +#[test] +fn test_stacks_vector_017() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_017()); +} + +#[test] +fn test_stacks_vector_018() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_018()); +} + +#[test] +fn test_stacks_vector_019() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_019()); +} + +#[test] +fn test_stacks_vector_020() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_020()); +} + +#[test] +fn test_stacks_vector_021() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_021()); +} + +#[test] +fn test_stacks_vector_022() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_022()); +} + +#[test] +fn test_stacks_vector_023() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_023()); +} + +#[test] +fn test_stacks_vector_024() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_024()); +} + +#[test] +fn test_stacks_vector_025() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_025()); +} + +#[test] +fn test_stacks_vector_026() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_026()); +} + +#[test] +fn test_stacks_vector_027() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_027()); +} + +#[test] +fn test_stacks_vector_028() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_028()); +} + +#[test] +fn test_stacks_vector_029() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_029()); +} + +#[test] +fn test_stacks_vector_030() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_030()); +} + +#[test] +fn test_stacks_vector_031() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_031()); +} + +#[test] +fn test_stacks_vector_032() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_032()); +} + +#[test] +fn test_stacks_vector_033() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_033()); +} + +#[test] +fn test_stacks_vector_034() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_034()); +} + +#[test] +fn test_stacks_vector_035() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_035()); +} + +#[test] +fn test_stacks_vector_036() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_036()); +} + +#[test] +fn test_stacks_vector_037() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_037()); +} + +#[test] +fn test_stacks_vector_038() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_038()); +} + +#[test] +fn test_stacks_vector_039() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_039()); +} + +#[test] +fn test_stacks_vector_040() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_040()); +} + +// #[test] +// fn test_stacks_vector_041() { +// process_stacks_blocks_and_check_expectations(helpers::shapes::get_vector_041()); +// } + +#[test] +fn test_stacks_vector_042() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_042()); +} + +#[test] +fn test_stacks_vector_043() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_043()); +} + +#[test] +fn test_stacks_vector_044() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_044()); +} + +#[test] +fn test_stacks_vector_045() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_045()); +} + +#[test] +fn test_stacks_vector_046() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_046()); +} + +#[test] +fn test_stacks_vector_047() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_047()); +} + +#[test] +fn test_stacks_vector_048() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_048()); +} + +#[test] +fn test_stacks_vector_049() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_049()); +} + +#[test] +fn test_stacks_vector_050() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_050()); +} + +#[test] +fn test_stacks_vector_051() { + process_stacks_blocks_and_check_expectations(helpers::stacks_shapes::get_vector_051()); +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/accounts.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/accounts.rs new file mode 100644 index 0000000..5208c6e --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/accounts.rs @@ -0,0 +1,79 @@ +pub fn deployer_stx_address() -> String { + format!("ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM") +} + +pub fn wallet_1_stx_address() -> String { + format!("ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5") +} + +pub fn wallet_2_stx_address() -> String { + format!("ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG") +} + +pub fn wallet_3_stx_address() -> String { + format!("ST2JHG361ZXG51QTKY2NQCVBPPRRE2KZB1HR05NNC") +} + +pub fn wallet_4_stx_address() -> String { + format!("ST2NEB84ASENDXKYGJPQW86YXQCEFEX2ZQPG87ND") +} + +pub fn wallet_5_stx_address() -> String { + format!("ST2REHHS5J3CERCRBEPMGH7921Q6PYKAADT7JP2VB") +} + +pub fn wallet_6_stx_address() -> String { + format!("ST3AM1A56AK2C1XAFJ4115ZSV26EB49BVQ10MGCS0") +} + +pub fn wallet_7_stx_address() -> String { + format!("ST3PF13W7Z0RRM42A8VZRVFQ75SV1K26RXEP8YGKJ") +} + +pub fn wallet_8_stx_address() -> String { + format!("ST3NBRSFKX28FQ2ZJ1MAKX58HKHSDGNV5N7R21XCP") +} + +pub fn wallet_9_stx_address() -> String { + format!("STNHKEPYEPJ8ET55ZZ0M5A34J0R3N5FM2CMMMAZ6") +} + +pub fn deployer_btc_address() -> String { + format!("mqVnk6NPRdhntvfm4hh9vvjiRkFDUuSYsH") +} + +pub fn wallet_1_btc_address() -> String { + format!("mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC") +} + +pub fn wallet_2_btc_address() -> String { + format!("muYdXKmX9bByAueDe6KFfHd5Ff1gdN9ErG") +} + +pub fn wallet_3_btc_address() -> String { + format!("mvZtbibDAAA3WLpY7zXXFqRa3T4XSknBX7") +} + +pub fn wallet_4_btc_address() -> String { + format!("mg1C76bNTutiCDV3t9nWhZs3Dc8LzUufj8") +} + +pub fn wallet_5_btc_address() -> String { + format!("mweN5WVqadScHdA81aATSdcVr4B6dNokqx") +} + +pub fn wallet_6_btc_address() -> String { + format!("mzxXgV6e4BZSsz8zVHm3TmqbECt7mbuErt") +} + +pub fn wallet_7_btc_address() -> String { + format!("n37mwmru2oaVosgfuvzBwgV2ysCQRrLko7") +} + +pub fn wallet_8_btc_address() -> String { + format!("n2v875jbJ4RjBnTjgbfikDfnwsDV5iUByw") +} + +pub fn wallet_9_btc_address() -> String { + format!("mjSrB3wS4xab3kYqFktwBzfTdPg367ZJ2d") +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_blocks.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_blocks.rs new file mode 100644 index 0000000..3b16acb --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_blocks.rs @@ -0,0 +1,140 @@ +use chainhook_types::{ + BitcoinBlockData, BitcoinBlockMetadata, BitcoinTransactionData, BlockIdentifier, +}; +use clarity_repl::clarity::util::hash::to_hex; + +pub fn generate_test_bitcoin_block( + fork_id: u8, + block_height: u64, + transactions: Vec, + parent: Option, +) -> BitcoinBlockData { + let mut hash = vec![ + fork_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let parent_block_identifier = match parent { + Some(parent) => { + assert_eq!(parent.block_identifier.index, block_height - 1); + parent.block_identifier.clone() + } + _ => { + let mut parent_hash = if (block_height - 1) == 1 { + vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ] + } else { + vec![ + fork_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ] + }; + parent_hash.append(&mut (block_height - 1).to_be_bytes().to_vec()); + BlockIdentifier { + index: block_height - 1, + hash: format!("0x{}", to_hex(&parent_hash[..])), + } + } + }; + hash.append(&mut block_height.to_be_bytes().to_vec()); + BitcoinBlockData { + block_identifier: BlockIdentifier { + index: block_height, + hash: format!("0x{}", to_hex(&hash[..])), + }, + parent_block_identifier, + timestamp: 0, + transactions, + metadata: BitcoinBlockMetadata {}, + } +} + +pub fn A1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(0, 1, vec![], parent) +} + +pub fn B1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 2, vec![], parent) +} + +pub fn B2(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(2, 2, vec![], parent) +} + +pub fn C1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 3, vec![], parent) +} + +pub fn C2(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(2, 3, vec![], parent) +} + +pub fn D1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 4, vec![], parent) +} + +pub fn D2(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(2, 4, vec![], parent) +} + +pub fn E1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 5, vec![], parent) +} + +pub fn E2(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(2, 5, vec![], parent) +} + +pub fn B3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 2, vec![], parent) +} + +pub fn C3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 3, vec![], parent) +} + +pub fn D3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 4, vec![], parent) +} + +pub fn E3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 5, vec![], parent) +} + +pub fn F1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 6, vec![], parent) +} + +pub fn F2(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(2, 6, vec![], parent) +} + +pub fn F3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 6, vec![], parent) +} + +pub fn G1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 7, vec![], parent) +} + +pub fn G2(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(2, 7, vec![], parent) +} + +pub fn G3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 7, vec![], parent) +} + +pub fn H1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 8, vec![], parent) +} + +pub fn H3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 8, vec![], parent) +} + +pub fn I1(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(1, 9, vec![], parent) +} + +pub fn I3(parent: Option) -> BitcoinBlockData { + generate_test_bitcoin_block(3, 9, vec![], parent) +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_shapes.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_shapes.rs new file mode 100644 index 0000000..ae82448 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/bitcoin_shapes.rs @@ -0,0 +1,2652 @@ +use crate::utils::Context; + +use super::super::BitcoinChainEventExpectation; +use super::bitcoin_blocks; +use chainhook_types::{BitcoinBlockData, BitcoinChainEvent}; +use hiro_system_kit::slog; + +pub fn expect_no_chain_update() -> BitcoinChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + None => true, + _ => false, + }, + "expected no Chain update, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_block( + expected_block: BitcoinBlockData, + confirmed_blocks: Vec, +) -> BitcoinChainEventExpectation { + expect_chain_updated_with_blocks(vec![expected_block], confirmed_blocks) +} + +pub fn expect_chain_updated_with_blocks( + expected_blocks: Vec, + confirmed_blocks: Vec, +) -> BitcoinChainEventExpectation { + let ctx = Context::empty(); + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(BitcoinChainEvent::ChainUpdatedWithBlocks(ref event)) => { + assert_eq!(expected_blocks.len(), event.new_blocks.len()); + for (expected_block, new_block) in expected_blocks.iter().zip(&event.new_blocks) + { + ctx.try_log(|logger| { + slog::debug!( + logger, + "Checking {} and {}", + expected_block.block_identifier, + new_block.block_identifier + ) + }); + assert!( + new_block + .block_identifier + .eq(&expected_block.block_identifier), + "{} ≠ {}", + new_block.block_identifier, + expected_block.block_identifier + ); + } + assert_eq!(confirmed_blocks.len(), event.confirmed_blocks.len()); + for (expected_block, confirmed_block) in + confirmed_blocks.iter().zip(&event.confirmed_blocks) + { + ctx.try_log(|logger| { + slog::debug!( + logger, + "Checking {} and {}", + expected_block.block_identifier, + confirmed_block.block_identifier + ) + }); + assert!( + confirmed_block + .block_identifier + .eq(&expected_block.block_identifier), + "{} ≠ {}", + confirmed_block.block_identifier, + expected_block.block_identifier + ); + } + + true + } + _ => false, + }, + "expected ChainUpdatedWithBlocks, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_block_reorg( + blocks_to_rollback: Vec, + blocks_to_apply: Vec, + _confirmed_blocks: Vec, +) -> BitcoinChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(BitcoinChainEvent::ChainUpdatedWithReorg(ref event)) => { + assert_eq!(blocks_to_rollback.len(), event.blocks_to_rollback.len()); + assert_eq!(blocks_to_apply.len(), event.blocks_to_apply.len()); + for (expected, block_update) in + blocks_to_rollback.iter().zip(&event.blocks_to_rollback) + { + assert!( + expected.block_identifier.eq(&block_update.block_identifier), + "{} ≠ {}", + expected.block_identifier, + block_update.block_identifier + ); + } + for (expected, block_update) in + blocks_to_apply.iter().zip(&event.blocks_to_apply) + { + assert!( + expected.block_identifier.eq(&block_update.block_identifier), + "{} ≠ {}", + expected.block_identifier, + block_update.block_identifier + ); + } + true + } + _ => false, + }, + "expected ChainUpdatedWithReorg, got {:?}", + chain_event_to_check + ); + }) +} + +// Test vectors: +// 001 to 020: Bitcoin anchored blocks received in order +// 021 to 040: Bitcoin anchored blocks received out of order + +/// Vector 001: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) +/// +pub fn get_vector_001() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + ] +} + +/// Vector 002: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) +/// \ B2(3) - C2(5) +/// +pub fn get_vector_002() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None)], + vec![bitcoin_blocks::B2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ] +} + +/// Vector 003: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_003() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ] +} + +/// Vector 004: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_004() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 005: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_005() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ] +} + +/// Vector 006: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_006() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ] +} + +/// Vector 007: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_007() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + ] +} + +/// Vector 008: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) - H1(10) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_008() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + ] +} + +/// Vector 009: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) - H1(10) - I1(11) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_009() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 010: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) - H1(10) - I1(11) +/// \ B2(4) - C2(5) - D2(12) +/// +pub fn get_vector_010() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 011: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(11) - I1(12) +/// \ \ E3(9) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_011() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 012: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(13) +/// \ \ E3(9) - F3(11) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_012() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + ] +} + +/// Vector 013: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_013() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 014: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) - H3(15) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_014() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + (bitcoin_blocks::H3(None), expect_no_chain_update()), + ] +} + +/// Vector 015: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) - H3(15) - I3(16) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_015() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + (bitcoin_blocks::H3(None), expect_no_chain_update()), + ( + bitcoin_blocks::I3(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + bitcoin_blocks::I1(None), + ], + vec![ + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + bitcoin_blocks::G3(None), + bitcoin_blocks::H3(None), + bitcoin_blocks::I3(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 016: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) - H3(15) - I3(16) +/// \ B2(4) - C2(5) - D2(17) +/// +pub fn get_vector_016() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_block( + bitcoin_blocks::H1(None), + vec![bitcoin_blocks::B1(None)], + ), + ), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_block( + bitcoin_blocks::I1(None), + vec![bitcoin_blocks::C1(None)], + ), + ), + (bitcoin_blocks::H3(None), expect_no_chain_update()), + ( + bitcoin_blocks::I3(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + bitcoin_blocks::I1(None), + ], + vec![ + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + bitcoin_blocks::G3(None), + bitcoin_blocks::H3(None), + bitcoin_blocks::I3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + ] +} + +/// Vector 017: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) +/// \ \ E3(9) - F3(11) - G3(12) +/// \ B2(4) - C2(5) - D2(13) - E2(14) - F2(15) - G2(16) +/// +pub fn get_vector_017() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_block( + bitcoin_blocks::G1(None), + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::G3(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + ], + vec![ + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + bitcoin_blocks::G3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + (bitcoin_blocks::G2(None), expect_no_chain_update()), + ] +} + +/// Vector 018: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) +/// \ \ E3(9) - F3(10) +/// \ B2(4) - C2(5) - D2(11) - E2(12) - F2(13) - G2(14) +/// +pub fn get_vector_018() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::F3(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::E1(None), bitcoin_blocks::F1(None)], + vec![ + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + ( + bitcoin_blocks::G2(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + ], + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + ] +} + +/// Vector 019: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(15) +/// \ \ E3(9) - F3(10) +/// \ B2(4) - C2(5) - D2(11) - E2(12) - F2(13) - G2(14) +/// +pub fn get_vector_019() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::F3(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::E1(None), bitcoin_blocks::F1(None)], + vec![ + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + ( + bitcoin_blocks::G2(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + ], + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![], + ), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + ] +} + +/// Vector 020: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(15) +/// \ \ E3(9) - F3(10) - G3(16) +/// \ B2(4) - C2(5) - D2(11) - E2(12) - F2(13) - G2(14) +/// +pub fn get_vector_020() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block(bitcoin_blocks::F1(None), vec![]), + ), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::F3(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::E1(None), bitcoin_blocks::F1(None)], + vec![ + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + ( + bitcoin_blocks::G2(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + bitcoin_blocks::F3(None), + ], + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + ] +} + +/// Vector 021: Generate the following blocks +/// +/// A1(1) - B1(3) - C1(2) +/// +pub fn get_vector_021() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ] +} + +/// Vector 022: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) +/// \ B2(5) - C2(4) +/// +pub fn get_vector_022() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ] +} + +/// Vector 023: Generate the following blocks +/// +/// A1(1) - B1(5) - C1(3) +/// \ B2(2) - C2(4) +/// +pub fn get_vector_023() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block(bitcoin_blocks::B2(None), vec![]), + ), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block(bitcoin_blocks::C2(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ] +} + +/// Vector 024: Generate the following blocks +/// +/// A1(1) - B1(5) - C1(4) - D1(6) +/// \ B2(2) - C2(3) +/// +pub fn get_vector_024() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block(bitcoin_blocks::B2(None), vec![]), + ), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block(bitcoin_blocks::C2(None), vec![]), + ), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block(bitcoin_blocks::D1(None), vec![]), + ), + ] +} + +/// Vector 025: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(5) - E1(6) +/// \ B2(3) - C2(7) +/// +pub fn get_vector_025() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None)], + vec![bitcoin_blocks::B2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block(bitcoin_blocks::D1(None), vec![]), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block(bitcoin_blocks::E1(None), vec![]), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ] +} + +/// Vector 026: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(8) - E1(7) - F1(6) +/// \ B2(5) - C2(4) +/// +pub fn get_vector_026() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 027: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(9) - E1(8) - F1(7) - G1(6) +/// \ B2(5) - C2(3) +/// +pub fn get_vector_027() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block(bitcoin_blocks::B1(None), vec![]), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block(bitcoin_blocks::C1(None), vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 028: Generate the following blocks +/// +/// A1(1) - B1(8) - C1(10) - D1(3) - E1(6) - F1(2) - G1(5) - H1(4) +/// \ B2(7) - C2(9) +/// +pub fn get_vector_028() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::H1(None), expect_no_chain_update()), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block(bitcoin_blocks::B2(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None)], + vec![bitcoin_blocks::B1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 029: Generate the following blocks +/// +/// A1(1) - B1(7) - C1(6) - D1(9) - E1(10) - F1(2) - G1(3) - H1(4) - I1(11) +/// \ B2(8) - C2(5) +/// +pub fn get_vector_029() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::H1(None), expect_no_chain_update()), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + ], + vec![bitcoin_blocks::A1(None), bitcoin_blocks::B1(None)], + ), + ), + ( + bitcoin_blocks::I1(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::I1(None)], + vec![bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 030: Generate the following blocks +/// +/// A1(1) - B1(9) - C1(8) - D1(7) - E1(6) - F1(5) - G1(4) - H1(3) - I1(2) +/// \ B2(11) - C2(10) +/// +pub fn get_vector_030() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::I1(None), expect_no_chain_update()), + (bitcoin_blocks::H1(None), expect_no_chain_update()), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + bitcoin_blocks::I1(None), + ], + vec![ + bitcoin_blocks::A1(None), + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + ], + ), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + (bitcoin_blocks::B2(None), expect_no_chain_update()), + ] +} + +/// Vector 031: Generate the following blocks +/// +/// A1(1) - B1(8) - C1(7) - D1(6) - E1(4) - F1(9) - G1(11) - H1(12) - I1(10) +/// \ \ E3(2) +/// \ B2(3) - C2(5) +/// +pub fn get_vector_031() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::B2(None)], vec![]), + ), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::C2(None)], vec![]), + ), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::F1(None)], vec![]), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + (bitcoin_blocks::I1(None), expect_no_chain_update()), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::G1(None)], + vec![bitcoin_blocks::A1(None)], + ), + ), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::H1(None), bitcoin_blocks::I1(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 032: Generate the following blocks +/// +/// A1(1) - B1(3) - C1(5) - D1(2) - E1(8) - F1(10) - G1(13) - H1(12) - I1(11) +/// \ \ D3(7) - E3(9) +/// \ B2(4) - C2(6) +/// +pub fn get_vector_032() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::B1(None)], vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None)], + vec![bitcoin_blocks::B2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + ], + vec![], + ), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None))), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::D1(None)], + vec![bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None)))], + vec![], + ), + ), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None)))], + vec![bitcoin_blocks::D1(None), bitcoin_blocks::E1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::E3(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::D1(None), bitcoin_blocks::E1(None)], + vec![ + bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None))), + bitcoin_blocks::E3(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None))), + bitcoin_blocks::E3(None), + ], + vec![ + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + ], + vec![], + ), + ), + (bitcoin_blocks::I1(None), expect_no_chain_update()), + (bitcoin_blocks::H1(None), expect_no_chain_update()), + ( + bitcoin_blocks::G1(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + bitcoin_blocks::I1(None), + ], + vec![ + bitcoin_blocks::A1(None), + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + ], + ), + ), + ] +} + +/// Vector 033: Generate the following blocks +/// +/// A1(1) - B1(12) - C1(13) - D1(14) - E1(9) - F1(6) - G1(5) - H1(4) - I1(2) +/// \ \ D3(10) - E3(7) - F3(3) +/// \ B2(11) - C2(8) +/// +pub fn get_vector_033() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::I1(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + (bitcoin_blocks::H1(None), expect_no_chain_update()), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + ( + bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None))), + expect_no_chain_update(), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![], + ), + ), + (bitcoin_blocks::B1(None), expect_no_chain_update()), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + bitcoin_blocks::F3(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::D3(Some(bitcoin_blocks::C1(None))), + bitcoin_blocks::E3(None), + bitcoin_blocks::F3(None), + ], + vec![ + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + bitcoin_blocks::I1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 034: Generate the following blocks +/// +/// A1(1) - B1(12) - C1(14) - D1(7) - E1(2) - F1(4) - G1(6) - H1(9) - I1(13) +/// \ \ C3(5) - D3(3) - E3(8) - F3(15) +/// \ B2(10) - C2(11) +/// +pub fn get_vector_034() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::D3(None), expect_no_chain_update()), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + ( + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + expect_no_chain_update(), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + (bitcoin_blocks::H1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::B2(None)], vec![]), + ), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::C2(None)], vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::I1(None), expect_no_chain_update()), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + ], + vec![ + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + bitcoin_blocks::H1(None), + bitcoin_blocks::I1(None), + ], + vec![], + ), + ), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ] +} + +/// Vector 035: Generate the following blocks +/// +/// A1(1) - B1(5) - C1(4) - D1(8) - E1(10) - F1(13) - G1(12) - H1(15) - I1(14) +/// \ \ C3(6) - D3(7) - E3(11) - F3(9) - G3(16) +/// \ B2(2) - C2(3) +/// +pub fn get_vector_035() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::B2(None)], vec![]), + ), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::C2(None)], vec![]), + ), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None), bitcoin_blocks::C2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None)))], + vec![], + ), + ), + ( + bitcoin_blocks::D3(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::D3(None)], vec![]), + ), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::E1(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + bitcoin_blocks::D3(None), + ], + vec![ + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::E3(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + ], + vec![ + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + bitcoin_blocks::F3(None), + ], + vec![], + ), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + ( + bitcoin_blocks::F1(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + bitcoin_blocks::F3(None), + ], + vec![ + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + bitcoin_blocks::G1(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::I1(None), expect_no_chain_update()), + ( + bitcoin_blocks::H1(None), + expect_chain_updated_with_blocks( + vec![bitcoin_blocks::H1(None), bitcoin_blocks::I1(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 036: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(9) - E1(16) - F1(6) - G1(15) +/// \ \ C3(6) - D3(7) - E3(17) - F3(11) - G3(12) +/// \ B2(3) - C2(8) - D2(5) - E2(14) - F2(13) - G2(10) +/// +pub fn get_vector_036() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::B1(None)], vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None)], + vec![bitcoin_blocks::B2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + ( + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None)))], + vec![], + ), + ), + ( + bitcoin_blocks::D3(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::D3(None)], vec![]), + ), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::G2(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + ( + bitcoin_blocks::E2(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C3(Some(bitcoin_blocks::B1(None))), + bitcoin_blocks::D3(None), + ], + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + ] +} + +/// Vector 037: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(9) - E1(16) - F1(6) - G1(15) +/// \ B3(6) - C3(7) - D3(17) - E3(11) - F3(12) +/// \ B2(3) - C2(8) - D2(5) - E2(14) - F2(13) - G2(10) +/// +pub fn get_vector_037() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks(vec![bitcoin_blocks::B1(None)], vec![]), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None)], + vec![bitcoin_blocks::B2(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B2(None)], + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![], + ), + ), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::B3(None), expect_no_chain_update()), + ( + bitcoin_blocks::C3(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B1(None), bitcoin_blocks::C1(None)], + vec![bitcoin_blocks::B3(None), bitcoin_blocks::C3(None)], + vec![], + ), + ), + ( + bitcoin_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![bitcoin_blocks::B3(None), bitcoin_blocks::C3(None)], + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + ], + vec![], + ), + ), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::G2(None), expect_no_chain_update()), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + ( + bitcoin_blocks::E2(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::D3(None), expect_no_chain_update()), + ] +} + +/// Vector 038: Generate the following blocks +/// +/// A1(1) - B1(16) - C1(6) - D1(5) - E1(4) - F1(3) +/// \ B3(17) - C3(10) - D3(9) - E3(8) - F3(7) +/// \ B2(18) - C2(15) - D2(14) - E2(13) - F2(12) - G2(11) +/// +pub fn get_vector_038() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + (bitcoin_blocks::D3(None), expect_no_chain_update()), + (bitcoin_blocks::C3(None), expect_no_chain_update()), + (bitcoin_blocks::G2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::B3(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::B1(None), + bitcoin_blocks::C1(None), + bitcoin_blocks::D1(None), + bitcoin_blocks::E1(None), + bitcoin_blocks::F1(None), + ], + vec![ + bitcoin_blocks::B3(None), + bitcoin_blocks::C3(None), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + bitcoin_blocks::F3(None), + ], + vec![], + ), + ), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![ + bitcoin_blocks::B3(None), + bitcoin_blocks::C3(None), + bitcoin_blocks::D3(None), + bitcoin_blocks::E3(None), + bitcoin_blocks::F3(None), + ], + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 039: Generate the following blocks +/// +/// A1(1) - B1(15) - C1(8) - D1(7) - E1(6) - F1(3) - G1(2) +/// \ \ E3(10) - F3(9) +/// \ B2(14) - C2(13) - D2(12) - E2(11) - F2(5) - G2(4) +/// +pub fn get_vector_039() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::G2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + (bitcoin_blocks::E3(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::B1(None), expect_no_chain_update()), + ] +} + +/// Vector 040: Generate the following blocks +/// +/// A1(1) - B1(16) - C1(6) - D1(5) - E1(4) - F1(3) - G1(2) +/// \ \ E3(9) - F3(8) - G3(7) +/// \ B2(15) - C2(14) - D2(13) - E2(12) - F2(11) - G2(10) +/// +pub fn get_vector_040() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![ + ( + bitcoin_blocks::A1(None), + expect_chain_updated_with_block(bitcoin_blocks::A1(None), vec![]), + ), + (bitcoin_blocks::G1(None), expect_no_chain_update()), + (bitcoin_blocks::F1(None), expect_no_chain_update()), + (bitcoin_blocks::E1(None), expect_no_chain_update()), + (bitcoin_blocks::D1(None), expect_no_chain_update()), + (bitcoin_blocks::C1(None), expect_no_chain_update()), + (bitcoin_blocks::G3(None), expect_no_chain_update()), + (bitcoin_blocks::F3(None), expect_no_chain_update()), + ( + bitcoin_blocks::E3(Some(bitcoin_blocks::D1(None))), + expect_no_chain_update(), + ), + (bitcoin_blocks::G2(None), expect_no_chain_update()), + (bitcoin_blocks::F2(None), expect_no_chain_update()), + (bitcoin_blocks::E2(None), expect_no_chain_update()), + (bitcoin_blocks::D2(None), expect_no_chain_update()), + (bitcoin_blocks::C2(None), expect_no_chain_update()), + ( + bitcoin_blocks::B2(None), + expect_chain_updated_with_blocks( + vec![ + bitcoin_blocks::B2(None), + bitcoin_blocks::C2(None), + bitcoin_blocks::D2(None), + bitcoin_blocks::E2(None), + bitcoin_blocks::F2(None), + bitcoin_blocks::G2(None), + ], + vec![bitcoin_blocks::A1(None)], + ), + ), + (bitcoin_blocks::B1(None), expect_no_chain_update()), + ] +} + +/// Vector 041: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(5) - E1(8) - F1(9) +/// \ C2(4) - D2(6) - E2(7) - F2(10) - G2(11) +/// +pub fn get_vector_041() -> Vec<(BitcoinBlockData, BitcoinChainEventExpectation)> { + vec![] +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/microblocks.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/microblocks.rs new file mode 100644 index 0000000..1d23ba7 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/microblocks.rs @@ -0,0 +1,154 @@ +use super::BlockEvent; +use chainhook_types::{ + BlockIdentifier, StacksMicroblockData, StacksMicroblockMetadata, StacksTransactionData, +}; +use clarity_repl::clarity::util::hash::to_hex; + +pub fn generate_test_microblock( + fork_id: u8, + microblock_height: u64, + transactions: Vec, + anchor: BlockEvent, + parent_microblock: Option, +) -> BlockEvent { + let mut hash = vec![ + fork_id, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let anchor = match anchor { + BlockEvent::Block(anchor) => anchor, + _ => unreachable!(), + }; + let parent_block_identifier = if microblock_height == 0 { + anchor.block_identifier.clone() + } else { + match parent_microblock { + Some(BlockEvent::Microblock(parent_microblock)) => { + assert_eq!( + parent_microblock.block_identifier.index, + microblock_height - 1 + ); + parent_microblock.block_identifier.clone() + } + _ => { + let mut parent_hash = vec![ + fork_id, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + parent_hash.append(&mut (microblock_height - 1).to_be_bytes().to_vec()); + + BlockIdentifier { + index: microblock_height - 1, + hash: to_hex(&parent_hash[..]), + } + } + } + }; + hash.append(&mut microblock_height.to_be_bytes().to_vec()); + BlockEvent::Microblock(StacksMicroblockData { + block_identifier: BlockIdentifier { + index: microblock_height, + hash: to_hex(&hash[..]), + }, + parent_block_identifier, + timestamp: 0, + transactions, + metadata: StacksMicroblockMetadata { + anchor_block_identifier: anchor.block_identifier, + }, + }) +} + +pub fn a1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 0, vec![], anchor, parent_microblock) +} + +pub fn a2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 0, vec![], anchor, parent_microblock) +} + +pub fn b1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 1, vec![], anchor, parent_microblock) +} + +pub fn b2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 1, vec![], anchor, parent_microblock) +} + +pub fn c1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 2, vec![], anchor, parent_microblock) +} + +pub fn c2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 2, vec![], anchor, parent_microblock) +} + +pub fn d1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 3, vec![], anchor, parent_microblock) +} + +pub fn d2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 3, vec![], anchor, parent_microblock) +} + +pub fn e1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 4, vec![], anchor, parent_microblock) +} + +pub fn e2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 4, vec![], anchor, parent_microblock) +} + +pub fn b3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 1, vec![], anchor, parent_microblock) +} + +pub fn c3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 2, vec![], anchor, parent_microblock) +} + +pub fn d3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 3, vec![], anchor, parent_microblock) +} + +pub fn e3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 4, vec![], anchor, parent_microblock) +} + +pub fn f1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 5, vec![], anchor, parent_microblock) +} + +pub fn f2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 5, vec![], anchor, parent_microblock) +} + +pub fn f3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 5, vec![], anchor, parent_microblock) +} + +pub fn g1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 6, vec![], anchor, parent_microblock) +} + +pub fn g2(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(2, 6, vec![], anchor, parent_microblock) +} + +pub fn g3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 6, vec![], anchor, parent_microblock) +} + +pub fn h1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 7, vec![], anchor, parent_microblock) +} + +pub fn h3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 7, vec![], anchor, parent_microblock) +} + +pub fn i1(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(1, 8, vec![], anchor, parent_microblock) +} + +pub fn i3(anchor: BlockEvent, parent_microblock: Option) -> BlockEvent { + generate_test_microblock(3, 8, vec![], anchor, parent_microblock) +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/mod.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/mod.rs new file mode 100644 index 0000000..bb49fc4 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/mod.rs @@ -0,0 +1,25 @@ +use chainhook_types::{StacksBlockData, StacksMicroblockData}; + +pub mod accounts; +#[allow(non_snake_case, unreachable_code)] +pub mod bitcoin_blocks; +pub mod bitcoin_shapes; +pub mod microblocks; +#[allow(non_snake_case, unreachable_code)] +pub mod stacks_blocks; +pub mod stacks_shapes; +pub mod transactions; + +pub enum BlockEvent { + Block(StacksBlockData), + Microblock(StacksMicroblockData), +} + +impl BlockEvent { + pub fn expect_block(self) -> StacksBlockData { + match self { + BlockEvent::Block(block_data) => block_data, + _ => panic!("expected block"), + } + } +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/stacks_blocks.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/stacks_blocks.rs new file mode 100644 index 0000000..a841881 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/stacks_blocks.rs @@ -0,0 +1,191 @@ +use super::BlockEvent; +use chainhook_types::{ + BlockIdentifier, StacksBlockData, StacksBlockMetadata, StacksTransactionData, +}; +use clarity_repl::clarity::util::hash::to_hex; + +pub fn generate_test_stacks_block( + fork_id: u8, + block_height: u64, + transactions: Vec, + parent: Option, +) -> BlockEvent { + let mut hash = vec![ + fork_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + let (parent_block_identifier, confirm_microblock_identifier) = match parent { + Some(BlockEvent::Block(parent)) => { + assert_eq!(parent.block_identifier.index, block_height - 1); + (parent.block_identifier.clone(), None) + } + Some(BlockEvent::Microblock(microblock_parent)) => { + assert_eq!( + microblock_parent.metadata.anchor_block_identifier.index, + block_height - 1 + ); + ( + microblock_parent.metadata.anchor_block_identifier.clone(), + Some(microblock_parent.block_identifier.clone()), + ) + } + _ => { + let mut parent_hash = if (block_height - 1) == 1 { + vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ] + } else { + vec![ + fork_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ] + }; + parent_hash.append(&mut (block_height - 1).to_be_bytes().to_vec()); + ( + BlockIdentifier { + index: block_height - 1, + hash: to_hex(&parent_hash[..]), + }, + None, + ) + } + }; + hash.append(&mut block_height.to_be_bytes().to_vec()); + BlockEvent::Block(StacksBlockData { + block_identifier: BlockIdentifier { + index: block_height, + hash: to_hex(&hash[..]), + }, + parent_block_identifier, + timestamp: 0, + transactions, + metadata: StacksBlockMetadata { + bitcoin_anchor_block_identifier: BlockIdentifier { + index: block_height - 1, + hash: format!(""), + }, + pox_cycle_index: 1, + pox_cycle_position: block_height.try_into().unwrap(), + pox_cycle_length: 100, + confirm_microblock_identifier, + }, + }) +} + +pub fn A1(parent: Option) -> BlockEvent { + generate_test_stacks_block(0, 1, vec![], parent) +} + +pub fn B1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 2, vec![], parent) +} + +pub fn B2(parent: Option) -> BlockEvent { + generate_test_stacks_block(2, 2, vec![], parent) +} + +pub fn C1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 3, vec![], parent) +} + +pub fn C2(parent: Option) -> BlockEvent { + generate_test_stacks_block(2, 3, vec![], parent) +} + +pub fn D1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 4, vec![], parent) +} + +pub fn D2(parent: Option) -> BlockEvent { + generate_test_stacks_block(2, 4, vec![], parent) +} + +pub fn E1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 5, vec![], parent) +} + +pub fn E2(parent: Option) -> BlockEvent { + generate_test_stacks_block(2, 5, vec![], parent) +} + +pub fn B3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 2, vec![], parent) +} + +pub fn C3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 3, vec![], parent) +} + +pub fn D3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 4, vec![], parent) +} + +pub fn E3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 5, vec![], parent) +} + +pub fn F1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 6, vec![], parent) +} + +pub fn F2(parent: Option) -> BlockEvent { + generate_test_stacks_block(2, 6, vec![], parent) +} + +pub fn F3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 6, vec![], parent) +} + +pub fn G1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 7, vec![], parent) +} + +pub fn G2(parent: Option) -> BlockEvent { + generate_test_stacks_block(2, 7, vec![], parent) +} + +pub fn G3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 7, vec![], parent) +} + +pub fn H1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 8, vec![], parent) +} + +pub fn H3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 8, vec![], parent) +} + +pub fn I1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 9, vec![], parent) +} + +pub fn I3(parent: Option) -> BlockEvent { + generate_test_stacks_block(3, 9, vec![], parent) +} + +pub fn J1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 10, vec![], parent) +} + +pub fn K1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 11, vec![], parent) +} + +pub fn L1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 12, vec![], parent) +} + +pub fn M1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 13, vec![], parent) +} + +pub fn N1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 14, vec![], parent) +} + +pub fn O1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 15, vec![], parent) +} + +pub fn P1(parent: Option) -> BlockEvent { + generate_test_stacks_block(1, 16, vec![], parent) +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/stacks_shapes.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/stacks_shapes.rs new file mode 100644 index 0000000..4821afa --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/stacks_shapes.rs @@ -0,0 +1,3494 @@ +use crate::utils::Context; + +use super::{super::StacksChainEventExpectation, BlockEvent}; +use super::{microblocks, stacks_blocks}; +use chainhook_types::StacksChainEvent; +use hiro_system_kit::slog; + +pub fn expect_no_chain_update() -> StacksChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + None => true, + _ => false, + }, + "expected no Chain update, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_block( + expected_block: BlockEvent, + confirmed_blocks: Vec, +) -> StacksChainEventExpectation { + expect_chain_updated_with_blocks(vec![expected_block], confirmed_blocks) +} + +pub fn expect_chain_updated_with_microblock( + expected_microblock: BlockEvent, +) -> StacksChainEventExpectation { + expect_chain_updated_with_microblocks(vec![expected_microblock]) +} + +pub fn expect_chain_updated_with_microblocks( + expected_microblocks: Vec, +) -> StacksChainEventExpectation { + let ctx = Context::empty(); + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(StacksChainEvent::ChainUpdatedWithMicroblocks(ref event)) => { + assert_eq!(expected_microblocks.len(), event.new_microblocks.len()); + for (expected_microblock, new_microblock) in + expected_microblocks.iter().zip(&event.new_microblocks) + { + let expected_microblock = match expected_microblock { + BlockEvent::Microblock(expected_microblock) => expected_microblock, + _ => unreachable!(), + }; + ctx.try_log(|logger| { + slog::debug!( + logger, + "Checking {} and {}", + expected_microblock.block_identifier, + new_microblock.block_identifier + ) + }); + assert!( + new_microblock + .block_identifier + .eq(&expected_microblock.block_identifier), + "{} ≠ {}", + new_microblock.block_identifier, + expected_microblock.block_identifier + ); + } + true + } + _ => false, + }, + "expected ChainUpdatedWithMicroblocks, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_blocks( + expected_blocks: Vec, + confirmed_blocks: Vec, +) -> StacksChainEventExpectation { + let ctx = Context::empty(); + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(StacksChainEvent::ChainUpdatedWithBlocks(ref event)) => { + assert_eq!(expected_blocks.len(), event.new_blocks.len()); + for (expected_block, new_block) in expected_blocks.iter().zip(&event.new_blocks) + { + let expected_block = match expected_block { + BlockEvent::Block(expected_block) => expected_block, + _ => unreachable!(), + }; + ctx.try_log(|logger| { + slog::debug!( + logger, + "Checking {} and {}", + expected_block.block_identifier, + new_block.block.block_identifier + ) + }); + assert!( + new_block + .block + .block_identifier + .eq(&expected_block.block_identifier), + "{} ≠ {}", + new_block.block.block_identifier, + expected_block.block_identifier + ); + } + assert_eq!(confirmed_blocks.len(), event.confirmed_blocks.len()); + for (expected_confirmed_block, confirmed_block) in + confirmed_blocks.iter().zip(&event.confirmed_blocks) + { + let expected_block = match expected_confirmed_block { + BlockEvent::Block(block) => block, + _ => unreachable!(), + }; + ctx.try_log(|logger| { + slog::debug!( + logger, + "Checking {} and {}", + expected_block.block_identifier, + confirmed_block.block_identifier + ) + }); + assert!( + confirmed_block + .block_identifier + .eq(&expected_block.block_identifier), + "{} ≠ {}", + confirmed_block.block_identifier, + expected_block.block_identifier + ); + } + + true + } + _ => false, + }, + "expected ChainUpdatedWithBlocks, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_block_and_microblock_updates( + expected_block: BlockEvent, + microblocks_to_rollback: Vec, + microblocks_to_apply: Vec, + _confirmed_blocks: Vec, +) -> StacksChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(StacksChainEvent::ChainUpdatedWithBlocks(ref event)) => { + assert_eq!(event.new_blocks.len(), 1); + assert_eq!( + microblocks_to_rollback.len(), + event.new_blocks[0].parent_microblocks_to_rollback.len() + ); + assert_eq!( + microblocks_to_apply.len(), + event.new_blocks[0].parent_microblocks_to_apply.len() + ); + let expected_block = match expected_block { + BlockEvent::Block(ref expected_block) => expected_block, + _ => unreachable!(), + }; + + assert!( + event.new_blocks[0] + .block + .block_identifier + .eq(&expected_block.block_identifier), + "{} ≠ {}", + event.new_blocks[0].block.block_identifier, + expected_block.block_identifier + ); + let expected_microblock_id = event.new_blocks[0] + .block + .metadata + .confirm_microblock_identifier + .as_ref() + .unwrap(); + let microblock_id = expected_block + .metadata + .confirm_microblock_identifier + .as_ref() + .unwrap(); + assert!( + &expected_microblock_id.eq(µblock_id), + "{} ≠ {}", + expected_microblock_id, + microblock_id + ); + + for (expected, microblock) in microblocks_to_rollback + .iter() + .zip(&event.new_blocks[0].parent_microblocks_to_rollback) + { + let expected = match expected { + BlockEvent::Microblock(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected.block_identifier.eq(µblock.block_identifier), + "{} ≠ {}", + expected.block_identifier, + microblock.block_identifier + ); + } + for (expected, microblock) in microblocks_to_apply + .iter() + .zip(&event.new_blocks[0].parent_microblocks_to_apply) + { + let expected = match expected { + BlockEvent::Microblock(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected.block_identifier.eq(µblock.block_identifier), + "{} ≠ {}", + expected.block_identifier, + microblock.block_identifier + ); + } + true + } + _ => false, + }, + "expected ChainUpdatedWithBlocks, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_block_reorg_and_microblock_updates( + previous_block: BlockEvent, + new_block: BlockEvent, + microblocks_to_rollback: Vec, + microblocks_to_apply: Vec, + _confirmed_blocks: Vec, +) -> StacksChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(StacksChainEvent::ChainUpdatedWithReorg(ref event)) => { + assert_eq!(event.blocks_to_apply.len(), 1); + assert_eq!(event.blocks_to_rollback.len(), 1); + assert_eq!( + microblocks_to_rollback.len(), + event.blocks_to_rollback[0] + .parent_microblocks_to_rollback + .len() + ); + assert_eq!( + microblocks_to_apply.len(), + event.blocks_to_apply[0].parent_microblocks_to_apply.len() + ); + let previous_block = match previous_block { + BlockEvent::Block(ref previous_block) => previous_block, + _ => unreachable!(), + }; + let new_block = match new_block { + BlockEvent::Block(ref new_block) => new_block, + _ => unreachable!(), + }; + assert!( + event.blocks_to_apply[0] + .block + .block_identifier + .eq(&new_block.block_identifier), + "{} ≠ {}", + event.blocks_to_apply[0].block.block_identifier, + new_block.block_identifier + ); + assert!( + event.blocks_to_rollback[0] + .block + .block_identifier + .eq(&previous_block.block_identifier), + "{} ≠ {}", + event.blocks_to_rollback[0].block.block_identifier, + previous_block.block_identifier + ); + + let expected_microblock_id = event.blocks_to_apply[0] + .block + .metadata + .confirm_microblock_identifier + .as_ref() + .unwrap(); + let microblock_id = new_block + .metadata + .confirm_microblock_identifier + .as_ref() + .unwrap(); + assert!( + &expected_microblock_id.eq(µblock_id), + "{} ≠ {}", + expected_microblock_id, + microblock_id + ); + + let expected_microblock_id = event.blocks_to_rollback[0] + .block + .metadata + .confirm_microblock_identifier + .as_ref() + .unwrap(); + let microblock_id = previous_block + .metadata + .confirm_microblock_identifier + .as_ref() + .unwrap(); + assert!( + &expected_microblock_id.eq(µblock_id), + "{} ≠ {}", + expected_microblock_id, + microblock_id + ); + + for (expected, microblock) in microblocks_to_rollback + .iter() + .zip(&event.blocks_to_rollback[0].parent_microblocks_to_rollback) + { + let expected = match expected { + BlockEvent::Microblock(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected.block_identifier.eq(µblock.block_identifier), + "{} ≠ {}", + expected.block_identifier, + microblock.block_identifier + ); + } + for (expected, microblock) in microblocks_to_apply + .iter() + .zip(&event.blocks_to_apply[0].parent_microblocks_to_apply) + { + let expected = match expected { + BlockEvent::Microblock(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected.block_identifier.eq(µblock.block_identifier), + "{} ≠ {}", + expected.block_identifier, + microblock.block_identifier + ); + } + true + } + _ => false, + }, + "expected ChainUpdatedWithBlocks, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_block_reorg( + blocks_to_rollback: Vec, + blocks_to_apply: Vec, + _confirmed_blocks: Vec, +) -> StacksChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(StacksChainEvent::ChainUpdatedWithReorg(ref event)) => { + assert_eq!(blocks_to_rollback.len(), event.blocks_to_rollback.len()); + assert_eq!(blocks_to_apply.len(), event.blocks_to_apply.len()); + for (expected, block_update) in + blocks_to_rollback.iter().zip(&event.blocks_to_rollback) + { + let expected = match expected { + BlockEvent::Block(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected + .block_identifier + .eq(&block_update.block.block_identifier), + "{} ≠ {}", + expected.block_identifier, + block_update.block.block_identifier + ); + } + for (expected, block_update) in + blocks_to_apply.iter().zip(&event.blocks_to_apply) + { + let expected = match expected { + BlockEvent::Block(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected + .block_identifier + .eq(&block_update.block.block_identifier), + "{} ≠ {}", + expected.block_identifier, + block_update.block.block_identifier + ); + } + true + } + _ => false, + }, + "expected ChainUpdatedWithReorg, got {:?}", + chain_event_to_check + ); + }) +} + +pub fn expect_chain_updated_with_microblock_reorg( + microblocks_to_rollback: Vec, + microblocks_to_apply: Vec, +) -> StacksChainEventExpectation { + Box::new(move |chain_event_to_check: Option| { + assert!( + match chain_event_to_check { + Some(StacksChainEvent::ChainUpdatedWithMicroblocksReorg(ref event)) => { + assert_eq!( + microblocks_to_rollback.len(), + event.microblocks_to_rollback.len() + ); + assert_eq!(microblocks_to_apply.len(), event.microblocks_to_apply.len()); + for (expected, microblock) in microblocks_to_rollback + .iter() + .zip(&event.microblocks_to_rollback) + { + let expected = match expected { + BlockEvent::Microblock(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected.block_identifier.eq(µblock.block_identifier), + "{} ≠ {}", + expected.block_identifier, + microblock.block_identifier + ); + } + for (expected, microblock) in + microblocks_to_apply.iter().zip(&event.microblocks_to_apply) + { + let expected = match expected { + BlockEvent::Microblock(expected) => expected, + _ => unreachable!(), + }; + assert!( + expected.block_identifier.eq(µblock.block_identifier), + "{} ≠ {}", + expected.block_identifier, + microblock.block_identifier + ); + } + true + } + _ => false, + }, + "expected ChainUpdatedWithMicroblocksReorg, got {:?}", + chain_event_to_check + ); + }) +} + +// Test vectors: +// 001 to 020: Stacks anchored blocks received in order +// 021 to 040: Stacks anchored blocks received out of order +// 041 to 060: Stacks anchored blocks received in order + microblocks received in order +// 061 to 080: Stacks anchored blocks received in order + microblocks received out of order +// 081 to 100: Stacks anchored blocks received out of order + microblocks received out of order + +/// Vector 001: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) +/// +pub fn get_vector_001() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + ] +} + +/// Vector 002: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) +/// \ B2(3) - C2(5) +/// +pub fn get_vector_002() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None)], + vec![stacks_blocks::B2(None)], + vec![], + ), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ] +} + +/// Vector 003: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_003() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ] +} + +/// Vector 004: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_004() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 005: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_005() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ] +} + +/// Vector 006: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_006() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ] +} + +/// Vector 007: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_007() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + ] +} + +/// Vector 008: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) - H1(10) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_008() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + ] +} + +/// Vector 009: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) - H1(10) - I1(11) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_009() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + ] +} + +/// Vector 010: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(9) - H1(10) - I1(11) +/// \ B2(4) - C2(5) - D2(12) +/// +pub fn get_vector_010() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + ] +} + +/// Vector 011: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(11) - I1(12) +/// \ \ E3(9) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_011() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + (stacks_blocks::E3(None), expect_no_chain_update()), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + ] +} + +/// Vector 012: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(13) +/// \ \ E3(9) - F3(11) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_012() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + (stacks_blocks::E3(None), expect_no_chain_update()), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + ] +} + +/// Vector 013: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_013() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + (stacks_blocks::E3(None), expect_no_chain_update()), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + (stacks_blocks::G3(None), expect_no_chain_update()), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + ] +} + +/// Vector 014: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) - H3(15) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_014() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + (stacks_blocks::E3(None), expect_no_chain_update()), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + (stacks_blocks::G3(None), expect_no_chain_update()), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + (stacks_blocks::H3(None), expect_no_chain_update()), + ] +} + +/// Vector 015: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) - H3(15) - I3(16) +/// \ B2(4) - C2(5) +/// +pub fn get_vector_015() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + (stacks_blocks::G3(None), expect_no_chain_update()), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + (stacks_blocks::H3(None), expect_no_chain_update()), + ( + stacks_blocks::I3(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + stacks_blocks::I1(None), + ], + vec![ + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + stacks_blocks::G3(None), + stacks_blocks::H3(None), + stacks_blocks::I3(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 016: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) - H1(12) - I1(14) +/// \ \ E3(9) - F3(11) - G3(13) - H3(15) - I3(16) +/// \ B2(4) - C2(5) - D2(17) +/// +pub fn get_vector_016() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + (stacks_blocks::G3(None), expect_no_chain_update()), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + (stacks_blocks::H3(None), expect_no_chain_update()), + ( + stacks_blocks::I3(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + stacks_blocks::I1(None), + ], + vec![ + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + stacks_blocks::G3(None), + stacks_blocks::H3(None), + stacks_blocks::I3(None), + ], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + ] +} + +/// Vector 017: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(10) +/// \ \ E3(9) - F3(11) - G3(12) +/// \ B2(4) - C2(5) - D2(13) - E2(14) - F2(15) - G2(16) +/// +pub fn get_vector_017() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::G3(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + ], + vec![ + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + stacks_blocks::G3(None), + ], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + (stacks_blocks::G2(None), expect_no_chain_update()), + ] +} + +/// Vector 018: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) +/// \ \ E3(9) - F3(10) +/// \ B2(4) - C2(5) - D2(11) - E2(12) - F2(13) - G2(14) +/// +pub fn get_vector_018() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::F3(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::E1(None), stacks_blocks::F1(None)], + vec![ + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + ], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + ( + stacks_blocks::G2(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + ], + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + ] +} + +/// Vector 019: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(15) +/// \ \ E3(9) - F3(10) +/// \ B2(4) - C2(5) - D2(11) - E2(12) - F2(13) - G2(14) +/// +pub fn get_vector_019() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::F3(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::E1(None), stacks_blocks::F1(None)], + vec![ + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + ], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + ( + stacks_blocks::G2(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + ], + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![], + ), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + ] +} + +/// Vector 020: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(6) - E1(7) - F1(8) - G1(15) +/// \ \ E3(9) - F3(10) - G3(16) +/// \ B2(4) - C2(5) - D2(11) - E2(12) - F2(13) - G2(14) +/// +pub fn get_vector_020() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::B2(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::F3(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::E1(None), stacks_blocks::F1(None)], + vec![ + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + ], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + ( + stacks_blocks::G2(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + stacks_blocks::F3(None), + ], + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::G3(None), expect_no_chain_update()), + ] +} + +/// Vector 021: Generate the following blocks +/// +/// A1(1) - B1(3) - C1(2) +/// +pub fn get_vector_021() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ] +} + +/// Vector 022: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) +/// \ B2(5) - C2(4) +/// +pub fn get_vector_022() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ] +} + +/// Vector 023: Generate the following blocks +/// +/// A1(1) - B1(5) - C1(3) +/// \ B2(2) - C2(4) +/// +pub fn get_vector_023() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block(stacks_blocks::B2(None), vec![]), + ), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block(stacks_blocks::C2(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ] +} + +/// Vector 024: Generate the following blocks +/// +/// A1(1) - B1(5) - C1(4) - D1(6) +/// \ B2(2) - C2(3) +/// +pub fn get_vector_024() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block(stacks_blocks::B2(None), vec![]), + ), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block(stacks_blocks::C2(None), vec![]), + ), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block(stacks_blocks::D1(None), vec![]), + ), + ] +} + +/// Vector 025: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(5) - E1(6) +/// \ B2(3) - C2(7) +/// +pub fn get_vector_025() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None)], + vec![stacks_blocks::B2(None)], + vec![], + ), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block(stacks_blocks::D1(None), vec![]), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + ] +} + +/// Vector 026: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(8) - E1(7) - F1(6) +/// \ B2(5) - C2(4) +/// +pub fn get_vector_026() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 027: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(9) - E1(8) - F1(7) - G1(6) +/// \ B2(5) - C2(3) +/// +pub fn get_vector_027() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 028: Generate the following blocks +/// +/// A1(1) - B1(8) - C1(10) - D1(3) - E1(6) - F1(2) - G1(5) - H1(4) +/// \ B2(7) - C2(9) +/// +pub fn get_vector_028() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::H1(None), expect_no_chain_update()), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block(stacks_blocks::B2(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None)], + vec![stacks_blocks::B1(None)], + vec![], + ), + ), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 029: Generate the following blocks +/// +/// A1(1) - B1(7) - C1(6) - D1(9) - E1(10) - F1(2) - G1(3) - H1(4) - I1(11) +/// \ B2(8) - C2(5) +/// +pub fn get_vector_029() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::H1(None), expect_no_chain_update()), + (stacks_blocks::C2(None), expect_no_chain_update()), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + ], + vec![stacks_blocks::A1(None), stacks_blocks::B1(None)], + ), + ), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::I1(None)], + vec![stacks_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 030: Generate the following blocks +/// +/// A1(1) - B1(9) - C1(8) - D1(7) - E1(6) - F1(5) - G1(4) - H1(3) - I1(2) +/// \ B2(11) - C2(10) +/// +pub fn get_vector_030() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::I1(None), expect_no_chain_update()), + (stacks_blocks::H1(None), expect_no_chain_update()), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + stacks_blocks::I1(None), + ], + vec![ + stacks_blocks::A1(None), + stacks_blocks::B1(None), + stacks_blocks::C1(None), + ], + ), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + (stacks_blocks::B2(None), expect_no_chain_update()), + ] +} + +/// Vector 031: Generate the following blocks +/// +/// A1(1) - B1(8) - C1(7) - D1(6) - E1(4) - F1(9) - G1(11) - H1(12) - I1(10) +/// \ \ E3(2) +/// \ B2(3) - C2(5) +/// +pub fn get_vector_031() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::E3(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::B2(None)], vec![]), + ), + (stacks_blocks::E1(None), expect_no_chain_update()), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::C2(None)], vec![]), + ), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::F1(None)], vec![]), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + (stacks_blocks::I1(None), expect_no_chain_update()), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::G1(None)], + vec![stacks_blocks::A1(None)], + ), + ), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::H1(None), stacks_blocks::I1(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 032: Generate the following blocks +/// +/// A1(1) - B1(3) - C1(5) - D1(2) - E1(8) - F1(10) - G1(13) - H1(12) - I1(11) +/// \ \ D3(7) - E3(9) +/// \ B2(4) - C2(6) +/// +pub fn get_vector_032() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::D1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::B1(None)], vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None)], + vec![stacks_blocks::B2(None)], + vec![], + ), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + ], + vec![], + ), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::D3(Some(stacks_blocks::C1(None))), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::D1(None)], + vec![stacks_blocks::D3(Some(stacks_blocks::C1(None)))], + vec![], + ), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::D3(Some(stacks_blocks::C1(None)))], + vec![stacks_blocks::D1(None), stacks_blocks::E1(None)], + vec![], + ), + ), + ( + stacks_blocks::E3(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::D1(None), stacks_blocks::E1(None)], + vec![ + stacks_blocks::D3(Some(stacks_blocks::C1(None))), + stacks_blocks::E3(None), + ], + vec![], + ), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::D3(Some(stacks_blocks::C1(None))), + stacks_blocks::E3(None), + ], + vec![ + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + ], + vec![], + ), + ), + (stacks_blocks::I1(None), expect_no_chain_update()), + (stacks_blocks::H1(None), expect_no_chain_update()), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::G1(None), + stacks_blocks::H1(None), + stacks_blocks::I1(None), + ], + vec![ + stacks_blocks::A1(None), + stacks_blocks::B1(None), + stacks_blocks::C1(None), + ], + ), + ), + ] +} + +/// Vector 033: Generate the following blocks +/// +/// A1(1) - B1(12) - C1(13) - D1(14) - E1(9) - F1(6) - G1(5) - H1(4) - I1(2) +/// \ \ D3(10) - E3(7) - F3(3) +/// \ B2(11) - C2(8) +/// +pub fn get_vector_033() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::I1(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + (stacks_blocks::H1(None), expect_no_chain_update()), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::E3(None), expect_no_chain_update()), + (stacks_blocks::C2(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + ( + stacks_blocks::D3(Some(stacks_blocks::C1(None))), + expect_no_chain_update(), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![], + ), + ), + (stacks_blocks::B1(None), expect_no_chain_update()), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + stacks_blocks::F3(None), + ], + vec![], + ), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::D3(Some(stacks_blocks::C1(None))), + stacks_blocks::E3(None), + stacks_blocks::F3(None), + ], + vec![ + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + stacks_blocks::I1(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 034: Generate the following blocks +/// +/// A1(1) - B1(12) - C1(14) - D1(7) - E1(2) - F1(4) - G1(6) - H1(9) - I1(13) +/// \ \ C3(5) - D3(3) - E3(8) - F3(15) +/// \ B2(10) - C2(11) +/// +pub fn get_vector_034() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::D3(None), expect_no_chain_update()), + (stacks_blocks::F1(None), expect_no_chain_update()), + ( + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + expect_no_chain_update(), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::E3(None), expect_no_chain_update()), + (stacks_blocks::H1(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::B2(None)], vec![]), + ), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::C2(None)], vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![ + stacks_blocks::B1(None), + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + ], + vec![], + ), + ), + (stacks_blocks::I1(None), expect_no_chain_update()), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + ], + vec![ + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + stacks_blocks::H1(None), + stacks_blocks::I1(None), + ], + vec![], + ), + ), + (stacks_blocks::F3(None), expect_no_chain_update()), + ] +} + +/// Vector 035: Generate the following blocks +/// +/// A1(1) - B1(5) - C1(4) - D1(8) - E1(10) - F1(13) - G1(12) - H1(15) - I1(14) +/// \ \ C3(6) - D3(7) - E3(11) - F3(9) - G3(16) +/// \ B2(2) - C2(3) +/// +pub fn get_vector_035() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::B2(None)], vec![]), + ), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::C2(None)], vec![]), + ), + (stacks_blocks::C1(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None), stacks_blocks::C2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + ( + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::C1(None)], + vec![stacks_blocks::C3(Some(stacks_blocks::B1(None)))], + vec![], + ), + ), + ( + stacks_blocks::D3(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::D3(None)], vec![]), + ), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + stacks_blocks::D3(None), + ], + vec![ + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::E3(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + ], + vec![ + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + stacks_blocks::F3(None), + ], + vec![], + ), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + stacks_blocks::F3(None), + ], + vec![ + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + stacks_blocks::G1(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + (stacks_blocks::I1(None), expect_no_chain_update()), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_blocks( + vec![stacks_blocks::H1(None), stacks_blocks::I1(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + ), + ), + ] +} + +/// Vector 036: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(9) - E1(16) - F1(6) - G1(15) +/// \ \ C3(6) - D3(7) - E3(17) - F3(11) - G3(12) +/// \ B2(3) - C2(8) - D2(5) - E2(14) - F2(13) - G2(10) +/// +pub fn get_vector_036() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::B1(None)], vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None)], + vec![stacks_blocks::B2(None)], + vec![], + ), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + ( + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::C1(None)], + vec![stacks_blocks::C3(Some(stacks_blocks::B1(None)))], + vec![], + ), + ), + ( + stacks_blocks::D3(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::D3(None)], vec![]), + ), + (stacks_blocks::C2(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::G2(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + (stacks_blocks::G3(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + ( + stacks_blocks::E2(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C3(Some(stacks_blocks::B1(None))), + stacks_blocks::D3(None), + ], + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::E3(None), expect_no_chain_update()), + ] +} + +/// Vector 037: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(4) - D1(9) - E1(16) - F1(6) - G1(15) +/// \ B3(6) - C3(7) - D3(17) - E3(11) - F3(12) +/// \ B2(3) - C2(8) - D2(5) - E2(14) - F2(13) - G2(10) +/// +pub fn get_vector_037() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks(vec![stacks_blocks::B1(None)], vec![]), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None)], + vec![stacks_blocks::B2(None)], + vec![], + ), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B2(None)], + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![], + ), + ), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::B3(None), expect_no_chain_update()), + ( + stacks_blocks::C3(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B1(None), stacks_blocks::C1(None)], + vec![stacks_blocks::B3(None), stacks_blocks::C3(None)], + vec![], + ), + ), + ( + stacks_blocks::C2(None), + expect_chain_updated_with_block_reorg( + vec![stacks_blocks::B3(None), stacks_blocks::C3(None)], + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + ], + vec![], + ), + ), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::G2(None), expect_no_chain_update()), + (stacks_blocks::E3(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + ( + stacks_blocks::E2(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::D3(None), expect_no_chain_update()), + ] +} + +/// Vector 038: Generate the following blocks +/// +/// A1(1) - B1(16) - C1(6) - D1(5) - E1(4) - F1(3) +/// \ B3(17) - C3(10) - D3(9) - E3(8) - F3(7) +/// \ B2(18) - C2(15) - D2(14) - E2(13) - F2(12) - G2(11) +/// +pub fn get_vector_038() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::C1(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + (stacks_blocks::E3(None), expect_no_chain_update()), + (stacks_blocks::D3(None), expect_no_chain_update()), + (stacks_blocks::C3(None), expect_no_chain_update()), + (stacks_blocks::G2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + ], + vec![], + ), + ), + ( + stacks_blocks::B3(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::B1(None), + stacks_blocks::C1(None), + stacks_blocks::D1(None), + stacks_blocks::E1(None), + stacks_blocks::F1(None), + ], + vec![ + stacks_blocks::B3(None), + stacks_blocks::C3(None), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + stacks_blocks::F3(None), + ], + vec![], + ), + ), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_block_reorg( + vec![ + stacks_blocks::B3(None), + stacks_blocks::C3(None), + stacks_blocks::D3(None), + stacks_blocks::E3(None), + stacks_blocks::F3(None), + ], + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![], + ), + ), + ] +} + +/// Vector 039: Generate the following blocks +/// +/// A1(1) - B1(15) - C1(8) - D1(7) - E1(6) - F1(3) - G1(2) +/// \ \ E3(10) - F3(9) +/// \ B2(14) - C2(13) - D2(12) - E2(11) - F2(5) - G2(4) +/// +pub fn get_vector_039() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::G2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::C1(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + (stacks_blocks::E3(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + (stacks_blocks::B1(None), expect_no_chain_update()), + ] +} + +/// Vector 040: Generate the following blocks +/// +/// A1(1) - B1(16) - C1(6) - D1(5) - E1(4) - F1(3) - G1(2) +/// \ \ E3(9) - F3(8) - G3(7) +/// \ B2(15) - C2(14) - D2(13) - E2(12) - F2(11) - G2(10) +/// +pub fn get_vector_040() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + (stacks_blocks::G1(None), expect_no_chain_update()), + (stacks_blocks::F1(None), expect_no_chain_update()), + (stacks_blocks::E1(None), expect_no_chain_update()), + (stacks_blocks::D1(None), expect_no_chain_update()), + (stacks_blocks::C1(None), expect_no_chain_update()), + (stacks_blocks::G3(None), expect_no_chain_update()), + (stacks_blocks::F3(None), expect_no_chain_update()), + ( + stacks_blocks::E3(Some(stacks_blocks::D1(None))), + expect_no_chain_update(), + ), + (stacks_blocks::G2(None), expect_no_chain_update()), + (stacks_blocks::F2(None), expect_no_chain_update()), + (stacks_blocks::E2(None), expect_no_chain_update()), + (stacks_blocks::D2(None), expect_no_chain_update()), + (stacks_blocks::C2(None), expect_no_chain_update()), + ( + stacks_blocks::B2(None), + expect_chain_updated_with_blocks( + vec![ + stacks_blocks::B2(None), + stacks_blocks::C2(None), + stacks_blocks::D2(None), + stacks_blocks::E2(None), + stacks_blocks::F2(None), + stacks_blocks::G2(None), + ], + vec![stacks_blocks::A1(None)], + ), + ), + (stacks_blocks::B1(None), expect_no_chain_update()), + ] +} + +/// Vector 041: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(5) - E1(8) - F1(9) +/// \ C2(4) - D2(6) - E2(7) - F2(10) - G2(11) +/// +pub fn get_vector_041() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![] +} + +/// Vector 042: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](5) - C1(6) +/// +pub fn get_vector_042() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::c1(stacks_blocks::B1(None), None)), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + ] +} + +/// Vector 043: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](5) - [d1](6) - [e1](7) - C1(8) +/// +pub fn get_vector_043() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::c1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::d1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::d1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::e1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::e1(stacks_blocks::B1(None), None)), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + ] +} + +/// Vector 044: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) +/// \ [a2](4) - [b2](5) +/// +pub fn get_vector_044() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::a2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + microblocks::b2(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + ), + ), + ] +} + +/// Vector 045: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](6) +/// \ [a2](4) - [b2](5) +/// +pub fn get_vector_045() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::a2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + microblocks::b2(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + ], + ), + ), + ] +} + +/// Vector 046: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](6) - [d1](7) +/// \ [a2](4) - [b2](5) +/// +pub fn get_vector_046() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::a2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + microblocks::b2(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::d1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::d1(stacks_blocks::B1(None), None)), + ), + ] +} + +/// Vector 047: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](6) - [d1](7) - C1(8) +/// \ [a2](4) - [b2](5) +/// +pub fn get_vector_047() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::a2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + microblocks::b2(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::d1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::d1(stacks_blocks::B1(None), None)), + ), + ( + stacks_blocks::C1(Some(microblocks::d1(stacks_blocks::B1(None), None))), + expect_chain_updated_with_block( + stacks_blocks::C1(Some(microblocks::d1(stacks_blocks::B1(None), None))), + vec![], + ), + ), + ] +} + +/// Vector 048: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](6) - [d1](7) +/// \ [a2](4) - [b2](5) - C1(8) +/// +pub fn get_vector_048() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::a2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + microblocks::b2(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::d1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::d1(stacks_blocks::B1(None), None)), + ), + ( + stacks_blocks::C1(Some(microblocks::b2(stacks_blocks::B1(None), None))), + expect_chain_updated_with_block_and_microblock_updates( + stacks_blocks::C1(Some(microblocks::b2(stacks_blocks::B1(None), None))), + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + microblocks::d1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![], + ), + ), + ] +} + +/// Vector 049: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](6) - [d1](7) - C1(10) +/// \ [a2](4) - [b2](5) - C2(9) +/// +pub fn get_vector_049() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + microblocks::a1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::a1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::b1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::b1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::a2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + microblocks::b2(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::c1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock_reorg( + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + ], + ), + ), + ( + microblocks::d1(stacks_blocks::B1(None), None), + expect_chain_updated_with_microblock(microblocks::d1(stacks_blocks::B1(None), None)), + ), + ( + microblocks::c2(stacks_blocks::B1(None), None), + expect_no_chain_update(), + ), + ( + stacks_blocks::C2(Some(microblocks::b2(stacks_blocks::B1(None), None))), + expect_chain_updated_with_block_and_microblock_updates( + stacks_blocks::C2(Some(microblocks::b2(stacks_blocks::B1(None), None))), + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + microblocks::d1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![], + ), + ), + ( + stacks_blocks::C1(Some(microblocks::d1(stacks_blocks::B1(None), None))), + expect_chain_updated_with_block_reorg_and_microblock_updates( + stacks_blocks::C2(Some(microblocks::b2(stacks_blocks::B1(None), None))), + stacks_blocks::C1(Some(microblocks::d1(stacks_blocks::B1(None), None))), + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + microblocks::d1(stacks_blocks::B1(None), None), + ], + vec![], + ), + ), + ] +} + +/// Vector 050: Generate the following blocks +/// +/// A1(1) - B1(2) - [a1](3) - [b1](4) - [c1](6) - [d1](7) - C1(10) +/// \ [a2](4) - [b2](5) - C2(9) - D2(12) +/// \ [c2](8) - C3(11) +/// +pub fn get_vector_050() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + let mut base = get_vector_049(); + base.append(&mut vec![( + stacks_blocks::C3(Some(microblocks::c2(stacks_blocks::B1(None), None))), + expect_chain_updated_with_block_reorg_and_microblock_updates( + stacks_blocks::C1(Some(microblocks::d1(stacks_blocks::B1(None), None))), + stacks_blocks::C3(Some(microblocks::c2(stacks_blocks::B1(None), None))), + vec![ + microblocks::a1(stacks_blocks::B1(None), None), + microblocks::b1(stacks_blocks::B1(None), None), + microblocks::c1(stacks_blocks::B1(None), None), + microblocks::d1(stacks_blocks::B1(None), None), + ], + vec![ + microblocks::a2(stacks_blocks::B1(None), None), + microblocks::b2(stacks_blocks::B1(None), None), + microblocks::c2(stacks_blocks::B1(None), None), + ], + vec![], + ), + )]); + base +} + +/// Vector 051: Generate the following blocks +/// +/// A1(1) - B1(2) - C1(3) - D1(1) - E1(2) - F1(3) - G1(1) - H1(2) - I1(3) - J1(1) - K1(2) - L1(3) - M1(1) - N1(2) - O1(3) - P1(1) +/// +pub fn get_vector_051() -> Vec<(BlockEvent, StacksChainEventExpectation)> { + vec![ + ( + stacks_blocks::A1(None), + expect_chain_updated_with_block(stacks_blocks::A1(None), vec![]), + ), + ( + stacks_blocks::B1(None), + expect_chain_updated_with_block(stacks_blocks::B1(None), vec![]), + ), + ( + stacks_blocks::C1(None), + expect_chain_updated_with_block(stacks_blocks::C1(None), vec![]), + ), + ( + stacks_blocks::D1(None), + expect_chain_updated_with_block(stacks_blocks::D1(None), vec![]), + ), + ( + stacks_blocks::E1(None), + expect_chain_updated_with_block(stacks_blocks::E1(None), vec![]), + ), + ( + stacks_blocks::F1(None), + expect_chain_updated_with_block(stacks_blocks::F1(None), vec![]), + ), + ( + stacks_blocks::G1(None), + expect_chain_updated_with_block(stacks_blocks::G1(None), vec![stacks_blocks::A1(None)]), + ), + ( + stacks_blocks::H1(None), + expect_chain_updated_with_block(stacks_blocks::H1(None), vec![stacks_blocks::B1(None)]), + ), + ( + stacks_blocks::I1(None), + expect_chain_updated_with_block(stacks_blocks::I1(None), vec![stacks_blocks::C1(None)]), + ), + ( + stacks_blocks::J1(None), + expect_chain_updated_with_block(stacks_blocks::J1(None), vec![stacks_blocks::D1(None)]), + ), + ( + stacks_blocks::K1(None), + expect_chain_updated_with_block(stacks_blocks::K1(None), vec![stacks_blocks::E1(None)]), + ), + ( + stacks_blocks::L1(None), + expect_chain_updated_with_block(stacks_blocks::L1(None), vec![stacks_blocks::F1(None)]), + ), + ( + stacks_blocks::M1(None), + expect_chain_updated_with_block(stacks_blocks::M1(None), vec![stacks_blocks::G1(None)]), + ), + ( + stacks_blocks::N1(None), + expect_chain_updated_with_block(stacks_blocks::N1(None), vec![stacks_blocks::H1(None)]), + ), + ( + stacks_blocks::O1(None), + expect_chain_updated_with_block(stacks_blocks::O1(None), vec![stacks_blocks::I1(None)]), + ), + ( + stacks_blocks::P1(None), + expect_chain_updated_with_block(stacks_blocks::P1(None), vec![stacks_blocks::J1(None)]), + ), + ] +} diff --git a/components/chainhook-event-observer/src/indexer/tests/helpers/transactions.rs b/components/chainhook-event-observer/src/indexer/tests/helpers/transactions.rs new file mode 100644 index 0000000..ca657a5 --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/helpers/transactions.rs @@ -0,0 +1,111 @@ +use std::collections::HashSet; + +use base58::FromBase58; +use bitcoincore_rpc::bitcoin::blockdata::opcodes; +use bitcoincore_rpc::bitcoin::blockdata::script::Builder as BitcoinScriptBuilder; +use chainhook_types::bitcoin::TxOut; +use chainhook_types::{ + BitcoinTransactionData, BitcoinTransactionMetadata, StacksContractCallData, + StacksTransactionData, StacksTransactionKind, StacksTransactionMetadata, + StacksTransactionReceipt, TransactionIdentifier, +}; +use clarity_repl::clarity::util::hash::to_hex; + +use super::accounts; + +pub fn generate_test_tx_stacks_contract_call( + txid: u64, + sender: &str, + contract_name: &str, + method: &str, + args: Vec<&str>, +) -> StacksTransactionData { + let mut hash = vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + hash.append(&mut txid.to_be_bytes().to_vec()); + + let contract_identifier = format!("{}.{}", accounts::deployer_stx_address(), contract_name); + + // Preparing metadata + let mut mutated_contracts_radius = HashSet::new(); + mutated_contracts_radius.insert(contract_identifier.to_string()); + + let mutated_assets_radius = HashSet::new(); + + let contract_calls_stack = HashSet::new(); + + let events = vec![]; + + StacksTransactionData { + transaction_identifier: TransactionIdentifier { + hash: to_hex(&hash[..]), + }, + operations: vec![], + metadata: StacksTransactionMetadata { + success: true, + raw_tx: format!("__raw_tx__"), + result: format!("(ok true)"), + sender: format!("{}", sender), + fee: 0, + nonce: 0, + kind: StacksTransactionKind::ContractCall(StacksContractCallData { + contract_identifier: contract_identifier.to_string(), + method: method.to_string(), + args: args.iter().map(|arg| arg.to_string()).collect::>(), + }), + execution_cost: None, + receipt: StacksTransactionReceipt { + mutated_contracts_radius, + mutated_assets_radius, + contract_calls_stack, + events, + }, + description: format!("contract call {}::{}", contract_identifier, method), + sponsor: None, + position: chainhook_types::StacksTransactionPosition::anchor_block(0), + proof: None, + }, + } +} + +pub fn generate_test_tx_bitcoin_p2pkh_transfer( + txid: u64, + _sender: &str, + recipient: &str, + amount: u64, +) -> BitcoinTransactionData { + let mut hash = vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + hash.append(&mut txid.to_be_bytes().to_vec()); + + // Preparing metadata + let pubkey_hash = recipient + .from_base58() + .expect("Unable to get bytes from btc address"); + let script = BitcoinScriptBuilder::new() + .push_opcode(opcodes::all::OP_DUP) + .push_opcode(opcodes::all::OP_HASH160) + .push_slice(&pubkey_hash[1..21]) + .push_opcode(opcodes::all::OP_EQUALVERIFY) + .push_opcode(opcodes::all::OP_CHECKSIG) + .into_script(); + let outputs = vec![TxOut { + value: amount, + script_pubkey: to_hex(script.as_bytes()), + }]; + + BitcoinTransactionData { + transaction_identifier: TransactionIdentifier { + hash: format!("0x{}", to_hex(&hash[..])), + }, + operations: vec![], + metadata: BitcoinTransactionMetadata { + inputs: vec![], + outputs, + stacks_operations: vec![], + proof: None, + }, + } +} diff --git a/components/chainhook-event-observer/src/indexer/tests/mod.rs b/components/chainhook-event-observer/src/indexer/tests/mod.rs new file mode 100644 index 0000000..94bccbb --- /dev/null +++ b/components/chainhook-event-observer/src/indexer/tests/mod.rs @@ -0,0 +1,44 @@ +pub mod helpers; +use crate::utils::Context; + +use self::helpers::BlockEvent; +use super::{BitcoinBlockPool, StacksBlockPool}; +use chainhook_types::{BitcoinBlockData, BitcoinChainEvent, StacksChainEvent}; + +pub type StacksChainEventExpectation = Box) -> ()>; + +pub fn process_stacks_blocks_and_check_expectations( + steps: Vec<(BlockEvent, StacksChainEventExpectation)>, +) { + let mut blocks_processor = StacksBlockPool::new(); + for (block_event, check_chain_event_expectations) in steps.into_iter() { + match block_event { + BlockEvent::Block(block) => { + let chain_event = blocks_processor + .process_block(block, &Context::empty()) + .unwrap(); + check_chain_event_expectations(chain_event); + } + BlockEvent::Microblock(microblock) => { + let chain_event = blocks_processor + .process_microblocks(vec![microblock], &Context::empty()) + .unwrap(); + check_chain_event_expectations(chain_event); + } + } + } +} + +pub type BitcoinChainEventExpectation = Box) -> ()>; + +pub fn process_bitcoin_blocks_and_check_expectations( + steps: Vec<(BitcoinBlockData, BitcoinChainEventExpectation)>, +) { + let mut blocks_processor = BitcoinBlockPool::new(); + for (block, check_chain_event_expectations) in steps.into_iter() { + let chain_event = blocks_processor + .process_block(block, &Context::empty()) + .unwrap(); + check_chain_event_expectations(chain_event); + } +} diff --git a/components/chainhook-event-observer/src/lib.rs b/components/chainhook-event-observer/src/lib.rs new file mode 100644 index 0000000..1717fcd --- /dev/null +++ b/components/chainhook-event-observer/src/lib.rs @@ -0,0 +1,18 @@ +#![allow(unused_imports)] + +#[macro_use] +extern crate rocket; + +#[macro_use] +extern crate serde; + +#[macro_use] +extern crate serde_derive; + +#[macro_use] +extern crate serde_json; + +pub mod chainhooks; +pub mod indexer; +pub mod observer; +pub mod utils; diff --git a/components/chainhook-event-observer/src/main.rs b/components/chainhook-event-observer/src/main.rs new file mode 100644 index 0000000..5c7a5d3 --- /dev/null +++ b/components/chainhook-event-observer/src/main.rs @@ -0,0 +1,175 @@ +#[macro_use] +extern crate rocket; + +#[macro_use] +extern crate serde_derive; + +#[macro_use] +extern crate serde_json; + +#[macro_use] +extern crate hiro_system_kit; + +pub mod chainhooks; +pub mod indexer; +pub mod observer; +pub mod utils; + +use crate::utils::Context; +use hiro_system_kit::log::setup_logger; +use hiro_system_kit::slog; + +use crate::chainhooks::types::ChainhookConfig; +use clap::Parser; +use ctrlc; +use observer::{EventHandler, EventObserverConfig, ObserverCommand}; +use std::collections::HashSet; +use std::fs::File; +use std::io::{BufReader, Read}; +use std::path::PathBuf; +use std::sync::mpsc::channel; + +/// Simple program to greet a person +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Path of the config to load + #[clap(short, long)] + config_path: Option, +} + +#[rocket::main] +async fn main() { + let context = Context { + logger: Some(setup_logger()), + tracer: false, + }; + + let args = Args::parse(); + let config_path = get_config_path_or_exit(&args.config_path, &context); + let config = EventObserverConfig::from_path(&config_path, &context); + let (command_tx, command_rx) = channel(); + let tx_terminator = command_tx.clone(); + + ctrlc::set_handler(move || { + tx_terminator + .send(ObserverCommand::Terminate) + .expect("Could not send signal on channel.") + }) + .expect("Error setting Ctrl-C handler"); + + let _ = observer::start_event_observer(config, command_tx, command_rx, None, context).await; +} + +#[derive(Serialize, Deserialize, Debug, Default)] +pub struct EventObserverConfigFile { + pub normalization_enabled: Option, + pub grpc_server_enabled: Option, + pub hooks_enabled: Option, + pub bitcoin_rpc_proxy_enabled: Option, + pub webhooks: Option>, + pub ingestion_port: Option, + pub control_port: Option, + pub bitcoin_node_username: String, + pub bitcoin_node_password: String, + pub bitcoin_node_rpc_url: String, + pub stacks_node_rpc_url: String, + pub operators: Option>, +} + +impl EventObserverConfig { + pub fn from_path(path: &PathBuf, ctx: &Context) -> EventObserverConfig { + let path = match File::open(path) { + Ok(path) => path, + Err(_e) => { + ctx.try_log(|logger| { + slog::error!( + logger, + "Error: unable to locate Clarinet.toml in current directory" + ) + }); + std::process::exit(1); + } + }; + let mut file_reader = BufReader::new(path); + let mut file_buffer = vec![]; + file_reader.read_to_end(&mut file_buffer).unwrap(); + + let file: EventObserverConfigFile = match toml::from_slice(&file_buffer[..]) { + Ok(s) => s, + Err(e) => { + ctx.try_log(|logger| error!(logger, "Unable to read config {}", e)); + std::process::exit(1); + } + }; + + EventObserverConfig::from_config_file(file, ctx) + } + + pub fn from_config_file( + mut config_file: EventObserverConfigFile, + _ctx: &Context, + ) -> EventObserverConfig { + let event_handlers = match config_file.webhooks.take() { + Some(webhooks) => webhooks + .into_iter() + .map(|h| EventHandler::WebHook(h)) + .collect::>(), + None => vec![], + }; + let mut operators = HashSet::new(); + if let Some(operator_keys) = config_file.operators.take() { + for operator_key in operator_keys.into_iter() { + operators.insert(operator_key); + } + } + + let config = EventObserverConfig { + normalization_enabled: config_file.normalization_enabled.unwrap_or(true), + grpc_server_enabled: config_file.grpc_server_enabled.unwrap_or(false), + hooks_enabled: config_file.hooks_enabled.unwrap_or(false), + chainhook_config: Some(ChainhookConfig::new()), + bitcoin_rpc_proxy_enabled: config_file.bitcoin_rpc_proxy_enabled.unwrap_or(false), + event_handlers: event_handlers, + ingestion_port: config_file + .ingestion_port + .unwrap_or(observer::DEFAULT_INGESTION_PORT), + control_port: config_file + .control_port + .unwrap_or(observer::DEFAULT_CONTROL_PORT), + bitcoin_node_username: config_file.bitcoin_node_username.clone(), + bitcoin_node_password: config_file.bitcoin_node_password.clone(), + bitcoin_node_rpc_url: config_file.bitcoin_node_rpc_url.clone(), + stacks_node_rpc_url: config_file.stacks_node_rpc_url.clone(), + operators, + display_logs: true, + }; + config + } +} + +fn get_config_path_or_exit(path: &Option, ctx: &Context) -> PathBuf { + if let Some(path) = path { + let manifest_path = PathBuf::from(path); + if !manifest_path.exists() { + ctx.try_log(|logger| slog::error!(logger, "Could not find Observer.toml")); + std::process::exit(1); + } + manifest_path + } else { + let mut current_dir = std::env::current_dir().unwrap(); + loop { + current_dir.push("Observer.toml"); + + if current_dir.exists() { + break current_dir; + } + current_dir.pop(); + + if !current_dir.pop() { + ctx.try_log(|logger| slog::error!(logger, "Could not find Observer.toml")); + std::process::exit(1); + } + } + } +} diff --git a/components/chainhook-event-observer/src/observer/mod.rs b/components/chainhook-event-observer/src/observer/mod.rs new file mode 100644 index 0000000..5554715 --- /dev/null +++ b/components/chainhook-event-observer/src/observer/mod.rs @@ -0,0 +1,1535 @@ +use crate::chainhooks::bitcoin::{ + evaluate_bitcoin_chainhooks_on_chain_event, handle_bitcoin_hook_action, + BitcoinChainhookOccurrence, BitcoinChainhookOccurrencePayload, +}; +use crate::chainhooks::stacks::{ + evaluate_stacks_chainhooks_on_chain_event, handle_stacks_hook_action, + StacksChainhookOccurrence, StacksChainhookOccurrencePayload, +}; +use crate::chainhooks::types::{ChainhookConfig, ChainhookSpecification}; +use crate::indexer::bitcoin::retrieve_full_block; +use crate::indexer::{self, Indexer, IndexerConfig}; +use crate::utils::Context; +use bitcoincore_rpc::bitcoin::{BlockHash, Txid}; +use bitcoincore_rpc::{Auth, Client, RpcApi}; +use chainhook_types::{ + BitcoinChainEvent, BitcoinNetwork, BlockIdentifier, StacksChainEvent, StacksNetwork, + TransactionIdentifier, +}; +use clarity_repl::clarity::util::hash::bytes_to_hex; +use hiro_system_kit; +use hiro_system_kit::slog; +use reqwest::Client as HttpClient; +use rocket::config::{self, Config, LogLevel}; +use rocket::data::{Limits, ToByteUnit}; +use rocket::http::Status; +use rocket::request::{self, FromRequest, Outcome, Request}; +use rocket::serde::json::{json, Json, Value as JsonValue}; +use rocket::serde::Deserialize; +use rocket::Shutdown; +use rocket::State; +use rocket_okapi::{openapi, openapi_get_routes, request::OpenApiFromRequest}; +use std::collections::{HashMap, HashSet}; +use std::error::Error; +use std::net::{IpAddr, Ipv4Addr}; +use std::str; +use std::str::FromStr; +use std::sync::mpsc::{Receiver, Sender}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::Duration; + +pub const DEFAULT_INGESTION_PORT: u16 = 20445; +pub const DEFAULT_CONTROL_PORT: u16 = 20446; + +#[derive(Deserialize)] +pub struct NewTransaction { + pub txid: String, + pub status: String, + pub raw_result: String, + pub raw_tx: String, +} + +#[derive(Clone, Debug)] +pub enum Event { + BitcoinChainEvent(BitcoinChainEvent), + StacksChainEvent(StacksChainEvent), +} + +// TODO(lgalabru): Support for GRPC? +#[derive(Clone, Debug)] +pub enum EventHandler { + WebHook(String), +} + +impl EventHandler { + async fn propagate_stacks_event(&self, stacks_event: &StacksChainEvent) { + match self { + EventHandler::WebHook(host) => { + let path = "chain-events/stacks"; + let url = format!("{}/{}", host, path); + let body = rocket::serde::json::serde_json::to_vec(&stacks_event).unwrap(); + let http_client = HttpClient::builder() + .timeout(Duration::from_secs(20)) + .build() + .expect("Unable to build http client"); + let _ = http_client + .post(url) + .header("Content-Type", "application/json") + .body(body) + .send() + .await; + // TODO(lgalabru): handle response errors + } + } + } + + async fn propagate_bitcoin_event(&self, bitcoin_event: &BitcoinChainEvent) { + match self { + EventHandler::WebHook(host) => { + let path = "chain-events/bitcoin"; + let url = format!("{}/{}", host, path); + let body = rocket::serde::json::serde_json::to_vec(&bitcoin_event).unwrap(); + let http_client = HttpClient::builder() + .timeout(Duration::from_secs(20)) + .build() + .expect("Unable to build http client"); + let _res = http_client + .post(url) + .header("Content-Type", "application/json") + .body(body) + .send() + .await; + // TODO(lgalabru): handle response errors + } + } + } + + async fn notify_bitcoin_transaction_proxied(&self) {} +} + +#[derive(Clone, Debug)] +pub struct EventObserverConfig { + pub normalization_enabled: bool, + pub grpc_server_enabled: bool, + pub hooks_enabled: bool, + pub chainhook_config: Option, + pub bitcoin_rpc_proxy_enabled: bool, + pub event_handlers: Vec, + pub ingestion_port: u16, + pub control_port: u16, + pub bitcoin_node_username: String, + pub bitcoin_node_password: String, + pub bitcoin_node_rpc_url: String, + pub stacks_node_rpc_url: String, + pub operators: HashSet, + pub display_logs: bool, +} + +#[derive(Deserialize, Debug)] +pub struct ContractReadonlyCall { + pub okay: bool, + pub result: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ObserverCommand { + PropagateBitcoinChainEvent(BitcoinChainEvent), + PropagateStacksChainEvent(StacksChainEvent), + PropagateStacksMempoolEvent(StacksChainMempoolEvent), + RegisterHook(ChainhookSpecification, ApiKey), + DeregisterBitcoinHook(String, ApiKey), + DeregisterStacksHook(String, ApiKey), + NotifyBitcoinTransactionProxied, + Terminate, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum StacksChainMempoolEvent { + TransactionsAdmitted(Vec), + TransactionDropped(String), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct MempoolAdmissionData { + pub tx_data: String, + pub tx_description: String, +} + +#[derive(Clone, Debug)] +pub enum ObserverEvent { + Error(String), + Fatal(String), + Info(String), + BitcoinChainEvent(BitcoinChainEvent), + StacksChainEvent(StacksChainEvent), + NotifyBitcoinTransactionProxied, + HookRegistered(ChainhookSpecification), + HookDeregistered(ChainhookSpecification), + BitcoinChainhookTriggered(BitcoinChainhookOccurrencePayload), + StacksChainhookTriggered(StacksChainhookOccurrencePayload), + HooksTriggered(usize), + Terminate, + StacksChainMempoolEvent(StacksChainMempoolEvent), +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +/// JSONRPC Request +pub struct BitcoinRPCRequest { + /// The name of the RPC call + pub method: String, + /// Parameters to the RPC call + pub params: serde_json::Value, + /// Identifier for this Request, which should appear in the response + pub id: serde_json::Value, + /// jsonrpc field, MUST be "2.0" + pub jsonrpc: serde_json::Value, +} + +#[derive(Debug, Clone)] +pub struct BitcoinConfig { + pub username: String, + pub password: String, + pub rpc_url: String, +} + +#[derive(Debug, Clone)] +pub struct ServicesConfig { + pub stacks_node_url: String, + pub bitcoin_node_url: String, +} + +#[derive(Debug, Clone)] +pub struct ChainhookStore { + entries: HashMap, +} + +impl ChainhookStore { + pub fn is_authorized(&self, token: Option) -> bool { + self.entries.contains_key(&ApiKey(token)) + } +} + +pub async fn start_event_observer( + mut config: EventObserverConfig, + observer_commands_tx: Sender, + observer_commands_rx: Receiver, + observer_events_tx: Option>, + ctx: Context, +) -> Result<(), Box> { + ctx.try_log(|logger| slog::info!(logger, "Event observer starting with config {:?}", config)); + + let indexer = Indexer::new(IndexerConfig { + stacks_node_rpc_url: config.stacks_node_rpc_url.clone(), + bitcoin_node_rpc_url: config.bitcoin_node_rpc_url.clone(), + bitcoin_node_rpc_username: config.bitcoin_node_username.clone(), + bitcoin_node_rpc_password: config.bitcoin_node_password.clone(), + stacks_network: StacksNetwork::Devnet, + bitcoin_network: BitcoinNetwork::Regtest, + }); + + let log_level = if config.display_logs { + if cfg!(feature = "cli") { + LogLevel::Critical + } else { + LogLevel::Debug + } + } else { + LogLevel::Off + }; + + let ingestion_port = config.ingestion_port; + let control_port = config.control_port; + let bitcoin_rpc_proxy_enabled = config.bitcoin_rpc_proxy_enabled; + let bitcoin_config = BitcoinConfig { + username: config.bitcoin_node_username.clone(), + password: config.bitcoin_node_password.clone(), + rpc_url: config.bitcoin_node_rpc_url.clone(), + }; + + let services_config = ServicesConfig { + stacks_node_url: config.bitcoin_node_rpc_url.clone(), + bitcoin_node_url: config.stacks_node_rpc_url.clone(), + }; + + let mut entries = HashMap::new(); + if config.operators.is_empty() { + // If authorization not required, we create a default ChainhookConfig + let mut hook_formation = ChainhookConfig::new(); + if let Some(ref mut initial_chainhook_config) = config.chainhook_config { + hook_formation + .stacks_chainhooks + .append(&mut initial_chainhook_config.stacks_chainhooks); + hook_formation + .bitcoin_chainhooks + .append(&mut initial_chainhook_config.bitcoin_chainhooks); + } + entries.insert(ApiKey(None), hook_formation); + } else { + for operator in config.operators.iter() { + entries.insert(ApiKey(Some(operator.clone())), ChainhookConfig::new()); + } + } + let chainhook_store = Arc::new(RwLock::new(ChainhookStore { entries })); + let indexer_rw_lock = Arc::new(RwLock::new(indexer)); + + let background_job_tx_mutex = Arc::new(Mutex::new(observer_commands_tx.clone())); + + let limits = Limits::default().limit("json", 4.megabytes()); + let mut shutdown_config = config::Shutdown::default(); + shutdown_config.ctrlc = false; + shutdown_config.grace = 0; + shutdown_config.mercy = 0; + + let ingestion_config = Config { + port: ingestion_port, + workers: 3, + address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + keep_alive: 5, + temp_dir: std::env::temp_dir().into(), + log_level: log_level.clone(), + cli_colors: false, + limits, + shutdown: shutdown_config, + ..Config::default() + }; + + let mut routes = rocket::routes![ + handle_ping, + handle_new_bitcoin_block, + handle_new_stacks_block, + handle_new_microblocks, + handle_new_mempool_tx, + handle_drop_mempool_tx, + handle_new_attachement, + handle_mined_block, + handle_mined_microblock, + ]; + + if bitcoin_rpc_proxy_enabled { + routes.append(&mut routes![handle_bitcoin_rpc_call]); + routes.append(&mut routes![handle_bitcoin_wallet_rpc_call]); + } + + let ctx_cloned = ctx.clone(); + let ignite = rocket::custom(ingestion_config) + .manage(indexer_rw_lock) + .manage(background_job_tx_mutex) + .manage(bitcoin_config) + .manage(ctx_cloned) + .manage(services_config) + .mount("/", routes) + .ignite() + .await?; + let ingestion_shutdown = Some(ignite.shutdown()); + + let _ = std::thread::spawn(move || { + let _ = hiro_system_kit::nestable_block_on(ignite.launch()); + }); + + let mut shutdown_config = config::Shutdown::default(); + shutdown_config.ctrlc = false; + shutdown_config.grace = 1; + shutdown_config.mercy = 1; + + let control_config = Config { + port: control_port, + workers: 1, + address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), + keep_alive: 5, + temp_dir: std::env::temp_dir().into(), + log_level, + cli_colors: false, + shutdown: shutdown_config, + ..Config::default() + }; + + let routes = openapi_get_routes![ + handle_ping, + handle_get_hooks, + handle_create_hook, + handle_delete_bitcoin_hook, + handle_delete_stacks_hook + ]; + + let background_job_tx_mutex = Arc::new(Mutex::new(observer_commands_tx.clone())); + let managed_chainhook_store = chainhook_store.clone(); + let ctx_cloned = ctx.clone(); + + let ignite = rocket::custom(control_config) + .manage(background_job_tx_mutex) + .manage(managed_chainhook_store) + .manage(ctx_cloned) + .mount("/", routes) + .ignite() + .await?; + let control_shutdown = Some(ignite.shutdown()); + + let _ = std::thread::spawn(move || { + let _ = hiro_system_kit::nestable_block_on(ignite.launch()); + }); + + // This loop is used for handling background jobs, emitted by HTTP calls. + start_observer_commands_handler( + config, + chainhook_store, + observer_commands_rx, + observer_events_tx, + ingestion_shutdown, + control_shutdown, + ctx, + ) + .await +} + +pub fn get_bitcoin_proof( + bitcoin_client_rpc: &Client, + transaction_identifier: &TransactionIdentifier, + block_identifier: &BlockIdentifier, +) -> Result { + let txid = Txid::from_str(&transaction_identifier.hash[2..]).expect("unable to build txid"); + let block_hash = + BlockHash::from_str(&block_identifier.hash[2..]).expect("unable to build block_hash"); + + let res = bitcoin_client_rpc.get_tx_out_proof(&vec![txid], Some(&block_hash)); + match res { + Ok(proof) => Ok(format!("0x{}", bytes_to_hex(&proof))), + Err(e) => Err(format!( + "failed collecting proof for transaction {}: {}", + transaction_identifier.hash, + e.to_string() + )), + } +} + +pub async fn start_observer_commands_handler( + config: EventObserverConfig, + chainhook_store: Arc>, + observer_commands_rx: Receiver, + observer_events_tx: Option>, + ingestion_shutdown: Option, + control_shutdown: Option, + ctx: Context, +) -> Result<(), Box> { + let mut chainhooks_occurrences_tracker: HashMap = HashMap::new(); + let event_handlers = config.event_handlers.clone(); + let mut chainhooks_lookup: HashMap = HashMap::new(); + + loop { + let command = match observer_commands_rx.recv() { + Ok(cmd) => cmd, + Err(e) => { + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::Error(format!("Channel error: {:?}", e))); + } + continue; + } + }; + match command { + ObserverCommand::Terminate => { + ctx.try_log(|logger| slog::info!(logger, "Handling Termination command")); + if let Some(ingestion_shutdown) = ingestion_shutdown { + ingestion_shutdown.notify(); + } + if let Some(control_shutdown) = control_shutdown { + control_shutdown.notify(); + } + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::Info("Terminating event observer".into())); + let _ = tx.send(ObserverEvent::Terminate); + } + break; + } + ObserverCommand::PropagateBitcoinChainEvent(chain_event) => { + ctx.try_log(|logger| { + slog::info!(logger, "Handling PropagateBitcoinChainEvent command") + }); + for event_handler in event_handlers.iter() { + event_handler.propagate_bitcoin_event(&chain_event).await; + } + // process hooks + let mut hooks_ids_to_deregister = vec![]; + let mut requests = vec![]; + + if config.hooks_enabled { + match chainhook_store.read() { + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to obtain lock {:?}", e) + }); + continue; + } + Ok(chainhook_store_reader) => { + let bitcoin_chainhooks = chainhook_store_reader + .entries + .values() + .map(|v| &v.bitcoin_chainhooks) + .flatten() + .collect::>(); + ctx.try_log(|logger| { + slog::info!( + logger, + "Evaluating {} bitcoin chainhooks registered", + bitcoin_chainhooks.len() + ) + }); + + let chainhooks_candidates = evaluate_bitcoin_chainhooks_on_chain_event( + &chain_event, + bitcoin_chainhooks, + ); + + ctx.try_log(|logger| { + slog::info!( + logger, + "{} bitcoin chainhooks positive evaluations", + chainhooks_candidates.len() + ) + }); + + let mut chainhooks_to_trigger = vec![]; + + for trigger in chainhooks_candidates.into_iter() { + let mut total_occurrences: u64 = *chainhooks_occurrences_tracker + .get(&trigger.chainhook.uuid) + .unwrap_or(&0); + total_occurrences += 1; + + let limit = trigger.chainhook.expire_after_occurrence.unwrap_or(0); + if limit == 0 || total_occurrences <= limit { + chainhooks_occurrences_tracker + .insert(trigger.chainhook.uuid.clone(), total_occurrences); + chainhooks_to_trigger.push(trigger); + } else { + hooks_ids_to_deregister.push(trigger.chainhook.uuid.clone()); + } + } + + let bitcoin_client_rpc = Client::new( + &config.bitcoin_node_rpc_url, + Auth::UserPass( + config.bitcoin_node_username.to_string(), + config.bitcoin_node_password.to_string(), + ), + ) + .expect("unable to build http client"); + + let mut proofs = HashMap::new(); + for hook_to_trigger in chainhooks_to_trigger.iter() { + for (transactions, block) in hook_to_trigger.apply.iter() { + for transaction in transactions.iter() { + if !proofs.contains_key(&transaction.transaction_identifier) + { + ctx.try_log(|logger| { + slog::info!( + logger, + "collecting proof for transaction {}", + transaction.transaction_identifier.hash + ) + }); + match get_bitcoin_proof( + &bitcoin_client_rpc, + &transaction.transaction_identifier, + &block.block_identifier, + ) { + Ok(proof) => { + proofs.insert( + &transaction.transaction_identifier, + proof, + ); + } + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "{e}") + }); + } + } + } + } + } + } + ctx.try_log(|logger| { + slog::info!( + logger, + "{} bitcoin chainhooks will be triggered", + chainhooks_to_trigger.len() + ) + }); + + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::HooksTriggered( + chainhooks_to_trigger.len(), + )); + } + for chainhook_to_trigger in chainhooks_to_trigger.into_iter() { + if let Some(result) = + handle_bitcoin_hook_action(chainhook_to_trigger, &proofs) + { + match result { + BitcoinChainhookOccurrence::Http(request) => { + requests.push(request); + } + BitcoinChainhookOccurrence::File(_path, _bytes) => ctx + .try_log(|logger| { + slog::info!( + logger, + "Writing to disk not supported in server mode" + ) + }), + BitcoinChainhookOccurrence::Data(payload) => { + if let Some(ref tx) = observer_events_tx { + let _ = tx.send( + ObserverEvent::BitcoinChainhookTriggered( + payload, + ), + ); + } + } + } + } + } + } + }; + } + ctx.try_log(|logger| { + slog::info!( + logger, + "{} bitcoin chainhooks to deregister", + hooks_ids_to_deregister.len() + ) + }); + + for hook_uuid in hooks_ids_to_deregister.iter() { + match chainhook_store.write() { + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to obtain lock {:?}", e) + }); + continue; + } + Ok(mut chainhook_store_writer) => { + chainhooks_lookup + .get(hook_uuid) + .and_then(|api_key| { + chainhook_store_writer.entries.get_mut(&api_key) + }) + .and_then(|hook_formation| { + hook_formation.deregister_bitcoin_hook(hook_uuid.clone()) + }) + .and_then(|chainhook| { + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::HookDeregistered( + ChainhookSpecification::Bitcoin(chainhook.clone()), + )); + } + Some(chainhook) + }); + } + } + } + + for request in requests.into_iter() { + // todo(lgalabru): collect responses for reporting + ctx.try_log(|logger| { + slog::info!( + logger, + "Dispatching request from bitcoin chainhook {:?}", + request + ) + }); + match request.send().await { + Ok(res) => { + if res.status().is_success() { + ctx.try_log(|logger| { + slog::info!(logger, "Trigger {} successful", res.url()) + }); + } else { + ctx.try_log(|logger| { + slog::warn!( + logger, + "Trigger {} failed with status {}", + res.url(), + res.status() + ) + }); + } + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!(logger, "Unable to build and send request {:?}", e) + }); + } + } + } + + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::BitcoinChainEvent(chain_event)); + } + } + ObserverCommand::PropagateStacksChainEvent(chain_event) => { + ctx.try_log(|logger| { + slog::info!(logger, "Handling PropagateStacksChainEvent command") + }); + for event_handler in event_handlers.iter() { + event_handler.propagate_stacks_event(&chain_event).await; + } + let mut hooks_ids_to_deregister = vec![]; + let mut requests = vec![]; + if config.hooks_enabled { + match chainhook_store.read() { + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to obtain lock {:?}", e) + }); + continue; + } + Ok(chainhook_store_reader) => { + let stacks_chainhooks = chainhook_store_reader + .entries + .values() + .map(|v| &v.stacks_chainhooks) + .flatten() + .collect(); + + // process hooks + let chainhooks_candidates = evaluate_stacks_chainhooks_on_chain_event( + &chain_event, + stacks_chainhooks, + &ctx, + ); + + let mut chainhooks_to_trigger = vec![]; + + for trigger in chainhooks_candidates.into_iter() { + let mut total_occurrences: u64 = *chainhooks_occurrences_tracker + .get(&trigger.chainhook.uuid) + .unwrap_or(&0); + total_occurrences += 1; + + let limit = trigger.chainhook.expire_after_occurrence.unwrap_or(0); + if limit == 0 || total_occurrences <= limit { + chainhooks_occurrences_tracker + .insert(trigger.chainhook.uuid.clone(), total_occurrences); + chainhooks_to_trigger.push(trigger); + } else { + hooks_ids_to_deregister.push(trigger.chainhook.uuid.clone()); + } + } + + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::HooksTriggered( + chainhooks_to_trigger.len(), + )); + } + let proofs = HashMap::new(); + for chainhook_to_trigger in chainhooks_to_trigger.into_iter() { + if let Some(result) = + handle_stacks_hook_action(chainhook_to_trigger, &proofs, &ctx) + { + match result { + StacksChainhookOccurrence::Http(request) => { + requests.push(request); + } + StacksChainhookOccurrence::File(_path, _bytes) => ctx + .try_log(|logger| { + slog::info!( + logger, + "Writing to disk not supported in server mode" + ) + }), + StacksChainhookOccurrence::Data(payload) => { + if let Some(ref tx) = observer_events_tx { + let _ = tx.send( + ObserverEvent::StacksChainhookTriggered( + payload, + ), + ); + } + } + } + } + } + } + } + } + + for hook_uuid in hooks_ids_to_deregister.iter() { + match chainhook_store.write() { + Err(e) => { + ctx.try_log(|logger| { + slog::error!(logger, "unable to obtain lock {:?}", e) + }); + continue; + } + Ok(mut chainhook_store_writer) => { + chainhooks_lookup + .get(hook_uuid) + .and_then(|api_key| { + chainhook_store_writer.entries.get_mut(&api_key) + }) + .and_then(|hook_formation| { + hook_formation.deregister_stacks_hook(hook_uuid.clone()) + }) + .and_then(|chainhook| { + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::HookDeregistered( + ChainhookSpecification::Stacks(chainhook.clone()), + )); + } + Some(chainhook) + }); + } + } + } + + for request in requests.into_iter() { + // todo(lgalabru): collect responses for reporting + ctx.try_log(|logger| { + slog::info!( + logger, + "Dispatching request from stacks chainhook {:?}", + request + ) + }); + match request.send().await { + Ok(res) => { + if res.status().is_success() { + ctx.try_log(|logger| { + slog::info!(logger, "Trigger {} successful", res.url()) + }); + } else { + ctx.try_log(|logger| { + slog::warn!( + logger, + "Trigger {} failed with status {}", + res.url(), + res.status() + ) + }); + } + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!(logger, "Unable to build and send request {:?}", e) + }); + } + } + } + + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::StacksChainEvent(chain_event)); + } + } + ObserverCommand::PropagateStacksMempoolEvent(mempool_event) => { + ctx.try_log(|logger| { + slog::info!(logger, "Handling PropagateStacksMempoolEvent command") + }); + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::StacksChainMempoolEvent(mempool_event)); + } + } + ObserverCommand::NotifyBitcoinTransactionProxied => { + ctx.try_log(|logger| { + slog::info!(logger, "Handling NotifyBitcoinTransactionProxied command") + }); + for event_handler in event_handlers.iter() { + event_handler.notify_bitcoin_transaction_proxied().await; + } + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::NotifyBitcoinTransactionProxied); + } + } + ObserverCommand::RegisterHook(hook, api_key) => match chainhook_store.write() { + Err(e) => { + ctx.try_log(|logger| slog::error!(logger, "unable to obtain lock {:?}", e)); + continue; + } + Ok(mut chainhook_store_writer) => { + ctx.try_log(|logger| slog::info!(logger, "Handling RegisterHook command")); + let hook_formation = match chainhook_store_writer.entries.get_mut(&api_key) { + Some(hook_formation) => hook_formation, + None => { + ctx.try_log(|logger| { + slog::error!( + logger, + "Unable to retrieve chainhooks associated with {:?}", + api_key + ) + }); + continue; + } + }; + let mut registered_hook = hook.clone(); + registered_hook.set_owner_uuid(&api_key); + hook_formation.register_hook(registered_hook.clone()); + chainhooks_lookup.insert(registered_hook.uuid().to_string(), api_key.clone()); + if let Some(ref tx) = observer_events_tx { + let _ = tx.send(ObserverEvent::HookRegistered(registered_hook)); + } + } + }, + ObserverCommand::DeregisterStacksHook(hook_uuid, api_key) => { + match chainhook_store.write() { + Err(e) => { + ctx.try_log(|logger| slog::error!(logger, "unable to obtain lock {:?}", e)); + continue; + } + Ok(mut chainhook_store_writer) => { + ctx.try_log(|logger| { + slog::info!(logger, "Handling DeregisterStacksHook command") + }); + let hook_formation = match chainhook_store_writer.entries.get_mut(&api_key) + { + Some(hook_formation) => hook_formation, + None => { + ctx.try_log(|logger| { + slog::error!( + logger, + "Unable to retrieve chainhooks associated with {:?}", + api_key + ) + }); + continue; + } + }; + chainhooks_lookup.remove(&hook_uuid); + let hook = hook_formation.deregister_stacks_hook(hook_uuid); + if let (Some(tx), Some(hook)) = (&observer_events_tx, hook) { + let _ = tx.send(ObserverEvent::HookDeregistered( + ChainhookSpecification::Stacks(hook), + )); + } + } + } + } + ObserverCommand::DeregisterBitcoinHook(hook_uuid, api_key) => { + match chainhook_store.write() { + Err(e) => { + ctx.try_log(|logger| slog::error!(logger, "unable to obtain lock {:?}", e)); + continue; + } + Ok(mut chainhook_store_writer) => { + ctx.try_log(|logger| { + slog::info!(logger, "Handling DeregisterBitcoinHook command") + }); + let hook_formation = match chainhook_store_writer.entries.get_mut(&api_key) + { + Some(hook_formation) => hook_formation, + None => { + ctx.try_log(|logger| { + slog::error!( + logger, + "Unable to retrieve chainhooks associated with {:?}", + api_key + ) + }); + continue; + } + }; + chainhooks_lookup.remove(&hook_uuid); + let hook = hook_formation.deregister_bitcoin_hook(hook_uuid); + if let (Some(tx), Some(hook)) = (&observer_events_tx, hook) { + let _ = tx.send(ObserverEvent::HookDeregistered( + ChainhookSpecification::Bitcoin(hook), + )); + } + } + } + } + } + } + Ok(()) +} + +#[openapi(skip)] +#[rocket::get("/ping", format = "application/json")] +pub fn handle_ping(ctx: &State) -> Json { + ctx.try_log(|logger| slog::info!(logger, "GET /ping")); + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/new_burn_block", format = "json", data = "")] +pub async fn handle_new_bitcoin_block( + indexer_rw_lock: &State>>, + bitcoin_config: &State, + marshalled_block: Json, + background_job_tx: &State>>>, + ctx: &State, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /new_burn_block")); + // Standardize the structure of the block, and identify the + // kind of update that this new block would imply, taking + // into account the last 7 blocks. + + let (block_height, block) = + match retrieve_full_block(bitcoin_config, marshalled_block.into_inner(), ctx).await { + Ok(block) => block, + Err(e) => { + ctx.try_log(|logger| { + slog::warn!(logger, "unable to retrieve_full_block: {}", e.to_string()) + }); + return Json(json!({ + "status": 500, + "result": "unable to retrieve_full_block", + })); + } + }; + + let chain_update = match indexer_rw_lock.inner().write() { + Ok(mut indexer) => indexer.handle_bitcoin_block(block_height, block, &ctx), + Err(e) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "unable to acquire indexer_rw_lock: {}", + e.to_string() + ) + }); + return Json(json!({ + "status": 500, + "result": "Unable to acquire lock", + })); + } + }; + + match chain_update { + Ok(Some(chain_event)) => { + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "unable to acquire background_job_tx: {}", + e.to_string() + ) + }); + return Json(json!({ + "status": 500, + "result": "Unable to acquire lock", + })); + } + }; + } + Ok(None) => { + ctx.try_log(|logger| slog::info!(logger, "unable to infer chain progress")); + } + Err(e) => { + ctx.try_log(|logger| slog::error!(logger, "unable to handle bitcoin block: {}", e)) + } + } + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/new_block", format = "application/json", data = "")] +pub fn handle_new_stacks_block( + indexer_rw_lock: &State>>, + marshalled_block: Json, + background_job_tx: &State>>>, + ctx: &State, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /new_block")); + // Standardize the structure of the block, and identify the + // kind of update that this new block would imply, taking + // into account the last 7 blocks. + // TODO(lgalabru): use _pox_info + let (_pox_info, chain_event) = match indexer_rw_lock.inner().write() { + Ok(mut indexer) => { + let pox_info = indexer.get_pox_info(); + let chain_event = + indexer.handle_stacks_marshalled_block(marshalled_block.into_inner(), &ctx); + (pox_info, chain_event) + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "unable to acquire indexer_rw_lock: {}", + e.to_string() + ) + }); + return Json(json!({ + "status": 500, + "result": "Unable to acquire lock", + })); + } + }; + + match chain_event { + Ok(Some(chain_event)) => { + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "unable to acquire background_job_tx: {}", + e.to_string() + ) + }); + return Json(json!({ + "status": 500, + "result": "Unable to acquire lock", + })); + } + }; + } + Ok(None) => { + ctx.try_log(|logger| slog::info!(logger, "unable to infer chain progress")); + } + Err(e) => ctx.try_log(|logger| slog::error!(logger, "{}", e)), + } + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post( + "/new_microblocks", + format = "application/json", + data = "" +)] +pub fn handle_new_microblocks( + indexer_rw_lock: &State>>, + marshalled_microblock: Json, + background_job_tx: &State>>>, + ctx: &State, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /new_microblocks")); + // Standardize the structure of the microblock, and identify the + // kind of update that this new microblock would imply + let chain_event = match indexer_rw_lock.inner().write() { + Ok(mut indexer) => { + let chain_event = indexer.handle_stacks_marshalled_microblock_trail( + marshalled_microblock.into_inner(), + &ctx, + ); + chain_event + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "unable to acquire background_job_tx: {}", + e.to_string() + ) + }); + return Json(json!({ + "status": 500, + "result": "Unable to acquire lock", + })); + } + }; + + match chain_event { + Ok(Some(chain_event)) => { + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + } + Err(e) => { + ctx.try_log(|logger| { + slog::warn!( + logger, + "unable to acquire background_job_tx: {}", + e.to_string() + ) + }); + return Json(json!({ + "status": 500, + "result": "Unable to acquire lock", + })); + } + }; + } + Ok(None) => { + ctx.try_log(|logger| slog::info!(logger, "unable to infer chain progress")); + } + Err(e) => { + ctx.try_log(|logger| slog::error!(logger, "unable to handle stacks microblock: {}", e)); + } + } + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/new_mempool_tx", format = "application/json", data = "")] +pub fn handle_new_mempool_tx( + raw_txs: Json>, + background_job_tx: &State>>>, + ctx: &State, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /new_mempool_tx")); + let transactions = raw_txs + .iter() + .map(|tx_data| { + let (tx_description, ..) = indexer::stacks::get_tx_description(&tx_data, &vec![]) + .expect("unable to parse transaction"); + MempoolAdmissionData { + tx_data: tx_data.clone(), + tx_description, + } + }) + .collect::>(); + + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::PropagateStacksMempoolEvent( + StacksChainMempoolEvent::TransactionsAdmitted(transactions), + )); + } + _ => {} + }; + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/drop_mempool_tx", format = "application/json")] +pub fn handle_drop_mempool_tx(ctx: &State) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /drop_mempool_tx")); + // TODO(lgalabru): use propagate mempool events + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[post("/attachments/new", format = "application/json")] +pub fn handle_new_attachement(ctx: &State) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /attachments/new")); + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/mined_block", format = "application/json", data = "")] +pub fn handle_mined_block(payload: Json, ctx: &State) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /mined_block {:?}", payload)); + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/mined_microblock", format = "application/json", data = "")] +pub fn handle_mined_microblock(payload: Json, ctx: &State) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /mined_microblock {:?}", payload)); + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(skip)] +#[post("/wallet", format = "application/json", data = "")] +pub async fn handle_bitcoin_wallet_rpc_call( + bitcoin_config: &State, + bitcoin_rpc_call: Json, + ctx: &State, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /wallet")); + + use base64::encode; + use reqwest::Client; + + let bitcoin_rpc_call = bitcoin_rpc_call.into_inner().clone(); + + let body = rocket::serde::json::serde_json::to_vec(&bitcoin_rpc_call).unwrap(); + + let token = encode(format!( + "{}:{}", + bitcoin_config.username, bitcoin_config.password + )); + + let url = format!("{}", bitcoin_config.rpc_url); + let client = Client::new(); + let builder = client + .post(&url) + .header("Content-Type", "application/json") + .header("Authorization", format!("Basic {}", token)) + .timeout(std::time::Duration::from_secs(5)); + + match builder.body(body).send().await { + Ok(res) => Json(res.json().await.unwrap()), + Err(_) => Json(json!({ + "status": 500 + })), + } +} + +#[openapi(skip)] +#[post("/", format = "application/json", data = "")] +pub async fn handle_bitcoin_rpc_call( + bitcoin_config: &State, + bitcoin_rpc_call: Json, + background_job_tx: &State>>>, + ctx: &State, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /")); + + use base64::encode; + use reqwest::Client; + + let bitcoin_rpc_call = bitcoin_rpc_call.into_inner().clone(); + let method = bitcoin_rpc_call.method.clone(); + + let body = rocket::serde::json::serde_json::to_vec(&bitcoin_rpc_call).unwrap(); + + let token = encode(format!( + "{}:{}", + bitcoin_config.username, bitcoin_config.password + )); + + ctx.try_log(|logger| { + slog::debug!( + logger, + "Forwarding {} request to {}", + method, + bitcoin_config.rpc_url + ) + }); + + let client = Client::new(); + let builder = client + .post(&bitcoin_config.rpc_url) + .header("Content-Type", "application/json") + .header("Authorization", format!("Basic {}", token)) + .timeout(std::time::Duration::from_secs(5)); + + if method == "sendrawtransaction" { + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::NotifyBitcoinTransactionProxied); + } + _ => {} + }; + } + + match builder.body(body).send().await { + Ok(res) => { + let payload = res.json().await.unwrap(); + ctx.try_log(|logger| slog::debug!(logger, "Responding with response {:?}", payload)); + Json(payload) + } + Err(_) => Json(json!({ + "status": 500 + })), + } +} + +#[openapi(tag = "Chainhooks")] +#[get("/v1/chainhooks", format = "application/json")] +pub fn handle_get_hooks( + chainhook_store: &State>>, + ctx: &State, + api_key: ApiKey, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "GET /v1/chainhooks")); + if let Ok(chainhook_store_reader) = chainhook_store.inner().read() { + match chainhook_store_reader.entries.get(&api_key) { + None => { + ctx.try_log(|logger| { + slog::info!( + logger, + "No chainhook registered for api key {:?}", + api_key.0 + ) + }); + Json(json!({ + "status": 404, + })) + } + Some(hooks) => { + let mut predicates = vec![]; + let mut stacks_predicates = hooks + .get_serialized_stacks_predicates() + .iter() + .map(|(uuid, network, predicate)| { + json!({ + "chain": "stacks", + "uuid": uuid, + "network": network, + "predicate": predicate, + }) + }) + .collect::>(); + predicates.append(&mut stacks_predicates); + let mut bitcoin_predicates = hooks + .get_serialized_bitcoin_predicates() + .iter() + .map(|(uuid, network, predicate)| { + json!({ + "chain": "bitcoin", + "uuid": uuid, + "network": network, + "predicate": predicate, + }) + }) + .collect::>(); + predicates.append(&mut bitcoin_predicates); + + Json(json!({ + "status": 200, + "result": predicates + })) + } + } + } else { + Json(json!({ + "status": 500, + "message": "too many requests", + })) + } +} + +#[openapi(tag = "Chainhooks")] +#[post("/v1/chainhooks", format = "application/json", data = "")] +pub fn handle_create_hook( + hook: Json, + background_job_tx: &State>>>, + ctx: &State, + api_key: ApiKey, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "POST /v1/chainhooks")); + let hook = hook.into_inner(); + if let Err(e) = hook.validate() { + return Json(json!({ + "status": 422, + "error": e, + })); + } + + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::RegisterHook(hook, api_key)); + } + _ => {} + }; + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(tag = "Chainhooks")] +#[delete("/v1/chainhooks/stacks/", format = "application/json")] +pub fn handle_delete_stacks_hook( + hook_uuid: String, + background_job_tx: &State>>>, + ctx: &State, + api_key: ApiKey, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "DELETE /v1/chainhooks/stacks/")); + + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::DeregisterStacksHook(hook_uuid, api_key)); + } + _ => {} + }; + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[openapi(tag = "Chainhooks")] +#[delete("/v1/chainhooks/bitcoin/", format = "application/json")] +pub fn handle_delete_bitcoin_hook( + hook_uuid: String, + background_job_tx: &State>>>, + ctx: &State, + api_key: ApiKey, +) -> Json { + ctx.try_log(|logger| slog::info!(logger, "DELETE /v1/chainhooks/stacks/")); + + let background_job_tx = background_job_tx.inner(); + match background_job_tx.lock() { + Ok(tx) => { + let _ = tx.send(ObserverCommand::DeregisterBitcoinHook(hook_uuid, api_key)); + } + _ => {} + }; + + Json(json!({ + "status": 200, + "result": "Ok", + })) +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash, OpenApiFromRequest)] +pub struct ApiKey(pub Option); + +#[derive(Debug)] +pub enum ApiKeyError { + Missing, + Invalid, + InternalError, +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for ApiKey { + type Error = ApiKeyError; + + async fn from_request(req: &'r Request<'_>) -> request::Outcome { + let state = req.rocket().state::>>(); + if let Some(chainhook_store_handle) = state { + if let Ok(chainhook_store_reader) = chainhook_store_handle.read() { + let key = req.headers().get_one("x-api-key"); + match key { + Some(key) => { + match chainhook_store_reader.is_authorized(Some(key.to_string())) { + true => Outcome::Success(ApiKey(Some(key.to_string()))), + false => Outcome::Failure((Status::BadRequest, ApiKeyError::Invalid)), + } + } + None => match chainhook_store_reader.is_authorized(None) { + true => Outcome::Success(ApiKey(None)), + false => Outcome::Failure((Status::BadRequest, ApiKeyError::Invalid)), + }, + } + } else { + Outcome::Failure((Status::InternalServerError, ApiKeyError::InternalError)) + } + } else { + Outcome::Failure((Status::InternalServerError, ApiKeyError::InternalError)) + } + } +} + +#[cfg(test)] +mod tests; diff --git a/components/chainhook-event-observer/src/observer/tests/mod.rs b/components/chainhook-event-observer/src/observer/tests/mod.rs new file mode 100644 index 0000000..4df57a2 --- /dev/null +++ b/components/chainhook-event-observer/src/observer/tests/mod.rs @@ -0,0 +1,990 @@ +use crate::chainhooks::types::{ + BitcoinChainhookSpecification, BitcoinPredicateType, BitcoinTransactionFilterPredicate, + ChainhookConfig, ChainhookSpecification, ExactMatchingRule, HookAction, Scope, + StacksChainhookSpecification, StacksContractCallBasedPredicate, + StacksTransactionFilterPredicate, +}; +use crate::indexer::tests::helpers::transactions::generate_test_tx_bitcoin_p2pkh_transfer; +use crate::indexer::tests::helpers::{ + accounts, bitcoin_blocks, stacks_blocks, transactions::generate_test_tx_stacks_contract_call, +}; +use crate::observer::{ + start_observer_commands_handler, ApiKey, ChainhookStore, EventObserverConfig, ObserverCommand, +}; +use crate::utils::Context; +use chainhook_types::{ + BitcoinChainEvent, BitcoinChainUpdatedWithBlocksData, BitcoinNetwork, StacksBlockUpdate, + StacksChainEvent, StacksChainUpdatedWithBlocksData, StacksNetwork, +}; +use hiro_system_kit; +use std::collections::{HashMap, HashSet}; +use std::sync::mpsc::{channel, Sender}; +use std::sync::{Arc, RwLock}; + +use super::ObserverEvent; + +fn generate_test_config() -> (EventObserverConfig, ChainhookStore) { + let operators = HashSet::new(); + let config = EventObserverConfig { + normalization_enabled: true, + grpc_server_enabled: false, + hooks_enabled: true, + chainhook_config: Some(ChainhookConfig::new()), + bitcoin_rpc_proxy_enabled: false, + event_handlers: vec![], + ingestion_port: 0, + control_port: 0, + bitcoin_node_username: "user".into(), + bitcoin_node_password: "user".into(), + bitcoin_node_rpc_url: "http://localhost:20443".into(), + stacks_node_rpc_url: "http://localhost:18443".into(), + operators, + display_logs: false, + }; + let mut entries = HashMap::new(); + entries.insert(ApiKey(None), ChainhookConfig::new()); + let chainhook_store = ChainhookStore { entries }; + (config, chainhook_store) +} + +fn stacks_chainhook_contract_call( + id: u8, + contract_identifier: &str, + method: &str, +) -> StacksChainhookSpecification { + let spec = StacksChainhookSpecification { + uuid: format!("{}", id), + name: format!("Chainhook {}", id), + owner_uuid: None, + network: StacksNetwork::Devnet, + version: 1, + start_block: None, + end_block: None, + expire_after_occurrence: None, + transaction_predicate: StacksTransactionFilterPredicate::ContractCall( + StacksContractCallBasedPredicate { + contract_identifier: contract_identifier.to_string(), + method: method.to_string(), + }, + ), + block_predicate: None, + action: HookAction::Noop, + capture_all_events: None, + decode_clarity_values: Some(true), + }; + spec +} + +fn bitcoin_chainhook_p2pkh( + id: u8, + address: &str, + expire_after_occurrence: Option, +) -> BitcoinChainhookSpecification { + let spec = BitcoinChainhookSpecification { + uuid: format!("{}", id), + name: format!("Chainhook {}", id), + owner_uuid: None, + network: BitcoinNetwork::Regtest, + version: 1, + start_block: None, + end_block: None, + expire_after_occurrence, + predicate: BitcoinTransactionFilterPredicate { + scope: Scope::Outputs, + kind: BitcoinPredicateType::P2pkh(ExactMatchingRule::Equals(address.to_string())), + }, + action: HookAction::Noop, + }; + spec +} + +fn generate_and_register_new_stacks_chainhook( + observer_commands_tx: &Sender, + observer_events_rx: &crossbeam_channel::Receiver, + id: u8, + contract_name: &str, + method: &str, +) -> StacksChainhookSpecification { + let contract_identifier = format!("{}.{}", accounts::deployer_stx_address(), contract_name); + let chainhook = stacks_chainhook_contract_call(id, &contract_identifier, method); + let _ = observer_commands_tx.send(ObserverCommand::RegisterHook( + ChainhookSpecification::Stacks(chainhook.clone()), + ApiKey(None), + )); + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookRegistered(registered_chainhook)) => { + assert_eq!( + ChainhookSpecification::Stacks(chainhook.clone()), + registered_chainhook + ); + true + } + _ => false, + }); + chainhook +} + +fn generate_and_register_new_bitcoin_chainhook( + observer_commands_tx: &Sender, + observer_events_rx: &crossbeam_channel::Receiver, + id: u8, + p2pkh_address: &str, + expire_after_occurrence: Option, +) -> BitcoinChainhookSpecification { + let chainhook = bitcoin_chainhook_p2pkh(id, &p2pkh_address, expire_after_occurrence); + let _ = observer_commands_tx.send(ObserverCommand::RegisterHook( + ChainhookSpecification::Bitcoin(chainhook.clone()), + ApiKey(None), + )); + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookRegistered(registered_chainhook)) => { + assert_eq!( + ChainhookSpecification::Bitcoin(chainhook.clone()), + registered_chainhook + ); + true + } + _ => false, + }); + chainhook +} + +#[test] +fn test_stacks_chainhook_register_deregister() { + let (observer_commands_tx, observer_commands_rx) = channel(); + let (observer_events_tx, observer_events_rx) = crossbeam_channel::unbounded(); + + let handle = std::thread::spawn(move || { + let (config, chainhook_store) = generate_test_config(); + let _ = hiro_system_kit::nestable_block_on(start_observer_commands_handler( + config, + Arc::new(RwLock::new(chainhook_store)), + observer_commands_rx, + Some(observer_events_tx), + None, + None, + Context::empty(), + )); + }); + + // Create and register a new chainhook + let chainhook = generate_and_register_new_stacks_chainhook( + &observer_commands_tx, + &observer_events_rx, + 1, + "counter", + "increment", + ); + + // Simulate a block that does not include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 0, + &accounts::wallet_1_stx_address(), + "counter", + "decrement", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 1, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 1, + &accounts::wallet_1_stx_address(), + "counter", + "increment", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 2, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 1); + true + } + _ => false, + }); + + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainhookTriggered(payload)) => { + assert_eq!(payload.apply.len(), 1); + assert_eq!(payload.apply[0].transactions.len(), 1); + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include 2 trigger + let transactions = vec![ + generate_test_tx_stacks_contract_call( + 1, + &accounts::wallet_1_stx_address(), + "counter", + "increment", + vec!["u1"], + ), + generate_test_tx_stacks_contract_call( + 2, + &accounts::wallet_2_stx_address(), + "counter", + "increment", + vec!["u2"], + ), + generate_test_tx_stacks_contract_call( + 3, + &accounts::wallet_3_stx_address(), + "counter", + "decrement", + vec!["u2"], + ), + ]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 2, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 1); + true + } + _ => false, + }); + + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainhookTriggered(payload)) => { + assert_eq!(payload.apply.len(), 1); + assert_eq!(payload.apply[0].transactions.len(), 2); + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + // Deregister the hook + let _ = observer_commands_tx.send(ObserverCommand::DeregisterStacksHook( + chainhook.uuid.clone(), + ApiKey(None), + )); + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookDeregistered(deregistered_chainhook)) => { + assert_eq!( + ChainhookSpecification::Stacks(chainhook), + deregistered_chainhook + ); + true + } + _ => false, + }); + + // Simulate a block that does not include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 2, + &accounts::wallet_1_stx_address(), + "counter", + "decrement", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 2, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 3, + &accounts::wallet_1_stx_address(), + "counter", + "increment", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 3, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + let _ = observer_commands_tx.send(ObserverCommand::Terminate); + handle.join().expect("unable to terminate thread"); +} + +#[test] +fn test_stacks_chainhook_auto_deregister() { + let (observer_commands_tx, observer_commands_rx) = channel(); + let (observer_events_tx, observer_events_rx) = crossbeam_channel::unbounded(); + + let handle = std::thread::spawn(move || { + let (config, chainhook_store) = generate_test_config(); + let _ = hiro_system_kit::nestable_block_on(start_observer_commands_handler( + config, + Arc::new(RwLock::new(chainhook_store)), + observer_commands_rx, + Some(observer_events_tx), + None, + None, + Context::empty(), + )); + }); + + // Create and register a new chainhook + let contract_identifier = format!("{}.{}", accounts::deployer_stx_address(), "counter"); + let mut chainhook = stacks_chainhook_contract_call(0, &contract_identifier, "increment"); + chainhook.expire_after_occurrence = Some(1); + + let _ = observer_commands_tx.send(ObserverCommand::RegisterHook( + ChainhookSpecification::Stacks(chainhook.clone()), + ApiKey(None), + )); + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookRegistered(registered_chainhook)) => { + assert_eq!( + ChainhookSpecification::Stacks(chainhook.clone()), + registered_chainhook + ); + true + } + _ => false, + }); + + // Simulate a block that does not include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 0, + &accounts::wallet_1_stx_address(), + "counter", + "decrement", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 1, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 1, + &accounts::wallet_1_stx_address(), + "counter", + "increment", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 2, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 1); + true + } + _ => false, + }); + + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainhookTriggered(_)) => { + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate another block that does include a trigger + let transactions = vec![generate_test_tx_stacks_contract_call( + 3, + &accounts::wallet_1_stx_address(), + "counter", + "increment", + vec!["u1"], + )]; + let chain_event = StacksChainEvent::ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData { + new_blocks: vec![StacksBlockUpdate::new( + stacks_blocks::generate_test_stacks_block(0, 3, transactions, None).expect_block(), + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateStacksChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should signal that a hook was deregistered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookDeregistered(deregistered_hook)) => { + assert_eq!(deregistered_hook.uuid(), chainhook.uuid); + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::StacksChainEvent(_)) => { + true + } + Ok(event) => { + println!("Unexpected event: {:?}", event); + false + } + Err(e) => { + println!("Error: {:?}", e); + false + } + }); + + let _ = observer_commands_tx.send(ObserverCommand::Terminate); + handle.join().expect("unable to terminate thread"); +} + +#[test] +fn test_bitcoin_chainhook_register_deregister() { + let (observer_commands_tx, observer_commands_rx) = channel(); + let (observer_events_tx, observer_events_rx) = crossbeam_channel::unbounded(); + + let handle = std::thread::spawn(move || { + let (config, chainhook_store) = generate_test_config(); + let _ = hiro_system_kit::nestable_block_on(start_observer_commands_handler( + config, + Arc::new(RwLock::new(chainhook_store)), + observer_commands_rx, + Some(observer_events_tx), + None, + None, + Context::empty(), + )); + }); + + // Create and register a new chainhook (wallet_2 received some sats) + let chainhook = generate_and_register_new_bitcoin_chainhook( + &observer_commands_tx, + &observer_events_rx, + 1, + &accounts::wallet_2_btc_address(), + None, + ); + + // Simulate a block that does not include a trigger (wallet_1 to wallet_3) + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 0, + &accounts::wallet_1_btc_address(), + &accounts::wallet_3_btc_address(), + 3, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 1, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + Ok(event) => { + println!("Unexpected event: {:?}", event); + false + } + Err(e) => { + println!("Error: {:?}", e); + false + } + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger (wallet_1 to wallet_2) + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 0, + &accounts::wallet_1_btc_address(), + &accounts::wallet_2_btc_address(), + 3, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 2, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 1); + true + } + _ => false, + }); + + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainhookTriggered(payload)) => { + assert_eq!(payload.apply.len(), 1); + assert_eq!(payload.apply[0].block.transactions.len(), 1); + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger (wallet_1 to wallet_2) + let transactions = vec![ + generate_test_tx_bitcoin_p2pkh_transfer( + 0, + &accounts::wallet_1_btc_address(), + &accounts::wallet_2_btc_address(), + 3, + ), + generate_test_tx_bitcoin_p2pkh_transfer( + 1, + &accounts::wallet_3_btc_address(), + &accounts::wallet_2_btc_address(), + 5, + ), + generate_test_tx_bitcoin_p2pkh_transfer( + 1, + &accounts::wallet_3_btc_address(), + &accounts::wallet_1_btc_address(), + 5, + ), + ]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 2, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 1); + true + } + _ => false, + }); + + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainhookTriggered(payload)) => { + assert_eq!(payload.apply.len(), 1); + assert_eq!(payload.apply[0].block.transactions.len(), 2); + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Deregister the hook + let _ = observer_commands_tx.send(ObserverCommand::DeregisterBitcoinHook( + chainhook.uuid.clone(), + ApiKey(None), + )); + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookDeregistered(deregistered_chainhook)) => { + assert_eq!( + ChainhookSpecification::Bitcoin(chainhook), + deregistered_chainhook + ); + true + } + _ => false, + }); + + // Simulate a block that does not include a trigger + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 2, + &accounts::wallet_1_btc_address(), + &accounts::wallet_3_btc_address(), + 1, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 2, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 3, + &accounts::wallet_1_btc_address(), + &accounts::wallet_2_btc_address(), + 1, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 3, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + let _ = observer_commands_tx.send(ObserverCommand::Terminate); + handle.join().expect("unable to terminate thread"); +} + +#[test] +fn test_bitcoin_chainhook_auto_deregister() { + let (observer_commands_tx, observer_commands_rx) = channel(); + let (observer_events_tx, observer_events_rx) = crossbeam_channel::unbounded(); + + let handle = std::thread::spawn(move || { + let (config, chainhook_store) = generate_test_config(); + let _ = hiro_system_kit::nestable_block_on(start_observer_commands_handler( + config, + Arc::new(RwLock::new(chainhook_store)), + observer_commands_rx, + Some(observer_events_tx), + None, + None, + Context::empty(), + )); + }); + + // Create and register a new chainhook (wallet_2 received some sats) + let chainhook = generate_and_register_new_bitcoin_chainhook( + &observer_commands_tx, + &observer_events_rx, + 1, + &accounts::wallet_2_btc_address(), + Some(1), + ); + + // Simulate a block that does not include a trigger (wallet_1 to wallet_3) + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 0, + &accounts::wallet_1_btc_address(), + &accounts::wallet_3_btc_address(), + 3, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 1, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger (wallet_1 to wallet_2) + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 0, + &accounts::wallet_1_btc_address(), + &accounts::wallet_2_btc_address(), + 3, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 2, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 1); + true + } + _ => false, + }); + + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainhookTriggered(_)) => { + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does not include a trigger + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 2, + &accounts::wallet_1_btc_address(), + &accounts::wallet_3_btc_address(), + 1, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 2, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + // Simulate a block that does include a trigger + let transactions = vec![generate_test_tx_bitcoin_p2pkh_transfer( + 3, + &accounts::wallet_1_btc_address(), + &accounts::wallet_2_btc_address(), + 1, + )]; + let chain_event = + BitcoinChainEvent::ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData { + new_blocks: vec![bitcoin_blocks::generate_test_bitcoin_block( + 0, + 3, + transactions, + None, + )], + confirmed_blocks: vec![], + }); + let _ = observer_commands_tx.send(ObserverCommand::PropagateBitcoinChainEvent(chain_event)); + // Should signal that no hook were triggered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HooksTriggered(len)) => { + assert_eq!(len, 0); + true + } + _ => false, + }); + // Should signal that a hook was deregistered + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::HookDeregistered(deregistered_hook)) => { + assert_eq!(deregistered_hook.uuid(), chainhook.uuid); + true + } + _ => false, + }); + + // Should propagate block + assert!(match observer_events_rx.recv() { + Ok(ObserverEvent::BitcoinChainEvent(_)) => { + true + } + _ => false, + }); + + let _ = observer_commands_tx.send(ObserverCommand::Terminate); + handle.join().expect("unable to terminate thread"); +} diff --git a/components/chainhook-event-observer/src/utils/mod.rs b/components/chainhook-event-observer/src/utils/mod.rs new file mode 100644 index 0000000..7dd2b86 --- /dev/null +++ b/components/chainhook-event-observer/src/utils/mod.rs @@ -0,0 +1,120 @@ +use chainhook_types::{ + BitcoinBlockData, BlockIdentifier, StacksBlockData, StacksMicroblockData, StacksTransactionData, +}; +use hiro_system_kit::slog::Logger; +use serde_json::Value as JsonValue; + +#[derive(Clone)] +pub struct Context { + pub logger: Option, + pub tracer: bool, +} + +impl Context { + pub fn empty() -> Context { + Context { + logger: None, + tracer: false, + } + } + + pub fn try_log(&self, closure: F) + where + F: FnOnce(&Logger), + { + if let Some(ref logger) = self.logger { + closure(logger) + } + } + + pub fn expect_logger(&self) -> &Logger { + self.logger.as_ref().unwrap() + } +} + +pub trait AbstractStacksBlock { + fn get_identifier(&self) -> &BlockIdentifier; + fn get_parent_identifier(&self) -> &BlockIdentifier; + fn get_transactions(&self) -> &Vec; + fn get_timestamp(&self) -> i64; + fn get_serialized_metadata(&self) -> JsonValue; +} + +impl AbstractStacksBlock for StacksBlockData { + fn get_identifier(&self) -> &BlockIdentifier { + &self.block_identifier + } + + fn get_parent_identifier(&self) -> &BlockIdentifier { + &self.parent_block_identifier + } + + fn get_transactions(&self) -> &Vec { + &self.transactions + } + + fn get_timestamp(&self) -> i64 { + self.timestamp + } + + fn get_serialized_metadata(&self) -> JsonValue { + json!(self.metadata) + } +} + +impl AbstractStacksBlock for StacksMicroblockData { + fn get_identifier(&self) -> &BlockIdentifier { + &self.block_identifier + } + + fn get_parent_identifier(&self) -> &BlockIdentifier { + &self.parent_block_identifier + } + + fn get_transactions(&self) -> &Vec { + &self.transactions + } + + fn get_timestamp(&self) -> i64 { + self.timestamp + } + + fn get_serialized_metadata(&self) -> JsonValue { + json!(self.metadata) + } +} + +pub trait AbstractBlock { + fn get_identifier(&self) -> &BlockIdentifier; + fn get_parent_identifier(&self) -> &BlockIdentifier; +} + +impl AbstractBlock for StacksBlockData { + fn get_identifier(&self) -> &BlockIdentifier { + &self.block_identifier + } + + fn get_parent_identifier(&self) -> &BlockIdentifier { + &self.parent_block_identifier + } +} + +impl AbstractBlock for StacksMicroblockData { + fn get_identifier(&self) -> &BlockIdentifier { + &self.block_identifier + } + + fn get_parent_identifier(&self) -> &BlockIdentifier { + &self.parent_block_identifier + } +} + +impl AbstractBlock for BitcoinBlockData { + fn get_identifier(&self) -> &BlockIdentifier { + &self.block_identifier + } + + fn get_parent_identifier(&self) -> &BlockIdentifier { + &self.parent_block_identifier + } +} diff --git a/components/chainhook-types-js/package.json b/components/chainhook-types-js/package.json new file mode 100644 index 0000000..50d61a3 --- /dev/null +++ b/components/chainhook-types-js/package.json @@ -0,0 +1,12 @@ +{ + "name": "@hirosystems/chainhook-types", + "version": "1.4.0", + "description": "", + "main": "dist/index.js", + "scripts": { + "build": "tsc --build", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC" +} diff --git a/components/chainhook-types-js/src/index.ts b/components/chainhook-types-js/src/index.ts new file mode 100644 index 0000000..eb45c7e --- /dev/null +++ b/components/chainhook-types-js/src/index.ts @@ -0,0 +1,1081 @@ +/** + * BitcoinChainUpdate provide informations about new blocks and confirmed blocks. + * @export + * @interface BitcoinChainUpdate + */ +export interface BitcoinChainUpdate { + /** + * @type {Array} + * @memberof BitcoinChainUpdate + */ + new_blocks: Array; + /** + * @type {Array} + * @memberof BitcoinChainUpdate + */ + confirmed_blocks: Array; +} + +/** + * StacksChainUpdate provide informations about new blocks and confirmed blocks. + * @export + * @interface StacksChainUpdate + */ +export interface StacksChainUpdate { + /** + * @type {Array} + * @memberof StacksChainUpdate + */ + new_blocks: Array; + /** + * @type {Array} + * @memberof StacksChainUpdate + */ + confirmed_blocks: Array; +} + +/** + * StacksBlockUpdate provide informations about new blocks and confirmed blocks. + * @export + * @interface StacksBlockUpdate + */ +export interface StacksBlockUpdate { + /** + * @type {Block} + * @memberof StacksBlockUpdate + */ + block: Block; + /** + * @type {Array} + * @memberof StacksBlockUpdate + */ + parent_microblocks_to_rollback: Array; + /** + * @type {Array} + * @memberof StacksBlockUpdate + */ + parent_microblocks_to_apply: Array; +} + +export interface BitcoinChainEvent { + apply: Block[]; + rollback: Block[]; + chainhook: { + uuid: string; + predicate: BitcoinPredicate; + }; +} + +export interface StacksChainEvent { + apply: Block[]; + rollback: Block[]; + chainhook: { + uuid: string; + predicate: StacksPredicate; + }; +} + +export interface StacksChainhook { + uuid: string; + predicate: StacksPredicate; +} + +export interface StacksPredicate { + type: StacksPredicateType; + rule: + | StacksContractCallBasedPredicate + | StacksPrintEventBasedPredicate + | StacksFtEventBasedPredicate + | StacksNftEventBasedPredicate + | StacksStxEventBasedPredicate; +} + +export enum StacksPredicateType { + ContractCall = "contract_call", + PrintEvent = "print_event", + FtEvent = "ft_event", + NftEvent = "nft_event", + StxEvent = "stx_event", +} + +export interface BitcoinChainhook { + uuid: string; + predicate: BitcoinPredicate; +} + +export enum BitcoinPredicateScope { + Inputs = "inputs", + Outputs = "outputs", +} + +export interface BitcoinPredicate { + scope: BitcoinPredicateScope; + type: BitcoinPredicateType; + rule: BitcoinPredicateMatchingRule; +} + +export enum BitcoinPredicateType { + Hex = "hex", + P2pkh = "p2pkh", + P2sh = "p2sh", + P2wpkh = "p2wpkh", + P2wsh = "p2wsh", + Script = "script", +} + +export interface BitcoinPredicateMatchingRule { + equals?: string; + starts_with?: string; + ends_with?: string; +} + +export interface StacksPrintEventBasedPredicate { + contract_identifier: string; + contains: string; +} + +export interface StacksFtEventBasedPredicate { + asset_identifier: string; + actions: string[]; +} + +export interface StacksContractCallBasedPredicate { + contract_identifier: string; + method: string; +} + +export interface StacksPrintEventBasedPredicate { + contract_identifier: string; + contains: string; +} + +export interface StacksFtEventBasedPredicate { + asset_identifier: string; + actions: string[]; +} + +export interface StacksNftEventBasedPredicate { + asset_identifier: string; + actions: string[]; +} + +export interface StacksStxEventBasedPredicate { + actions: string[]; +} + +/** + * In blockchains with sharded state, the SubNetworkIdentifier is required to query some object on a specific shard. This identifier is optional for all non-sharded blockchains. + * @export + * @interface SubNetworkIdentifier + */ +export interface SubNetworkIdentifier { + /** + * @type {string} + * @memberof SubNetworkIdentifier + */ + network: string; + /** + * @type {object} + * @memberof SubNetworkIdentifier + */ + metadata?: object; +} + +/** + * The network_identifier specifies which network a particular object is associated with. + * @export + * @interface NetworkIdentifier + */ +export interface NetworkIdentifier { + /** + * @type {string} + * @memberof NetworkIdentifier + */ + blockchain: string; + /** + * If a blockchain has a specific chain-id or network identifier, it should go in this field. It is up to the client to determine which network-specific identifier is mainnet or testnet. + * @type {string} + * @memberof NetworkIdentifier + */ + network: string; + /** + * @type {SubNetworkIdentifier} + * @memberof NetworkIdentifier + */ + sub_network_identifier?: SubNetworkIdentifier; +} + +/** + * Used by RelatedTransaction to indicate the direction of the relation (i.e. cross-shard/cross-network sends may reference `backward` to an earlier transaction and async execution may reference `forward`). Can be used to indicate if a transaction relation is from child to parent or the reverse. + * @export + * @enum {string} + */ +export enum Direction { + forward = "forward", + backward = "backward", +} + +/** + * The related_transaction allows implementations to link together multiple transactions. An unpopulated network identifier indicates that the related transaction is on the same network. + * @export + * @interface RelatedTransaction + */ +export interface RelatedTransaction { + /** + * @type {NetworkIdentifier} + * @memberof RelatedTransaction + */ + network_identifier?: NetworkIdentifier; + /** + * @type {TransactionIdentifier} + * @memberof RelatedTransaction + */ + transaction_identifier: TransactionIdentifier; + /** + * @type {Direction} + * @memberof RelatedTransaction + */ + direction: Direction; +} + +/** + * The transaction_identifier uniquely identifies a transaction in a particular network and block or in the mempool. + * @export + * @interface TransactionIdentifier + */ +export interface TransactionIdentifier { + /** + * Any transactions that are attributable only to a block (ex: a block event) should use the hash of the block as the identifier. + * @type {string} + * @memberof TransactionIdentifier + */ + hash: string; +} + +/** + * StacksTransactionMetadata contain an specific data about Stacks transactions. + * @export + * @interface StacksTransactionMetadata + */ +export interface StacksTransactionMetadata { + /** + * @type {boolean} + * @memberof StacksTransactionMetadata + */ + success: boolean; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + result: string; + /** + * @type {string[]} + * @memberof StacksTransactionMetadata + */ + events: string[]; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + description: string; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + raw_tx: string; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + sender: string; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + sponsor?: string; + /** + * @type {number} + * @memberof StacksTransactionMetadata + */ + fee: number; + /** + * @type {number} + * @memberof StacksTransactionMetadata + */ + nonce: number; + /** + * @type {StacksTransactionKind} + * @memberof StacksTransactionMetadata + */ + kind: StacksTransactionKind; + /** + * @type {StacksTransactionReceipt} + * @memberof StacksTransactionMetadata + */ + receipt: StacksTransactionReceipt; + /** + * @type {StacksTransactionExecutionCost} + * @memberof StacksTransactionMetadata + */ + execution_cost?: StacksTransactionExecutionCost; + /** + * @type {AnchorBlockPosition | MicroBlockPosition} + * @memberof StacksTransactionMetadata + */ + position: AnchorBlockPosition | MicroBlockPosition; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + proof?: string; +} + +/** + * MicroBlockPosition + * @export + * @interface MicroBlockPosition + */ + export interface MicroBlockPosition { + micro_block_identifier: BlockIdentifier, + index: number +} + +/** + * AnchorBlockPosition + * @export + * @interface AnchorBlockPosition + */ + export interface AnchorBlockPosition { + index: number +} + +export interface StacksTransactionReceipt { + /** + * @type {string[]} + * @memberof StacksTransactionReceipt + */ + mutated_contracts_radius: string[]; + /** + * @type {string[]} + * @memberof StacksTransactionReceipt + */ + mutated_assets_radius: string[]; + /** + * @type {StacksTransactionEvent[]} + * @memberof StacksTransactionReceipt + */ + events: StacksTransactionEvent[]; +} + +export interface StacksTransactionEvent { + type: StacksTransactionEventType; + data: + | StacksSTXTransferEventData + | StacksSTXMintEventData + | StacksSTXLockEventData + | StacksSTXBurnEventData + | StacksNFTTransferEventData + | StacksNFTMintEventData + | StacksNFTBurnEventData + | StacksFTTransferEventData + | StacksFTMintEventData + | StacksFTBurnEventData + | StacksDataVarSetEventData + | StacksDataMapInsertEventData + | StacksDataMapUpdateEventData + | StacksDataMapDeleteEventData + | StacksSmartContractEventData; +} + +export interface StacksContractDeploymentData { + /** + * @type {string} + * @memberof StacksContractDeploymentData + */ + contract_identifier: string; + /** + * @type {string[]} + * @memberof StacksContractDeploymentData + */ + code: string[]; +} + +export interface StacksTransactionExecutionCost { + /** + * @type {number} + * @memberof StacksTransactionExecutionCost + */ + write_length: number; + /** + * @type {number} + * @memberof StacksTransactionExecutionCost + */ + write_count: number; + /** + * @type {number} + * @memberof StacksTransactionExecutionCost + */ + read_length: number; + /** + * @type {number} + * @memberof StacksTransactionExecutionCost + */ + read_count: number; + /** + * @type {number} + * @memberof StacksTransactionExecutionCost + */ + runtime: number; +} + +export enum StacksTransactionKind { + ContractCall = "ContractCall", + ContractDeployment = "ContractDeployment", + NativeTokenTransfer = "NativeTokenTransfer", + Coinbase = "Coinbase", + Other = "Other", +} + +export enum StacksTransactionEventType { + StacksSTXTransferEvent = "STXTransferEvent", + StacksSTXMintEvent = "STXMintEvent", + StacksSTXLockEvent = "STXLockEvent", + StacksSTXBurnEvent = "STXBurnEvent", + StacksNFTTransferEvent = "NFTTransferEvent", + StacksNFTMintEvent = "NFTMintEvent", + StacksNFTBurnEvent = "NFTBurnEvent", + StacksFTTransferEvent = "FTTransferEvent", + StacksFTMintEvent = "FTMintEvent", + StacksFTBurnEvent = "FTBurnEvent", + StacksDataVarSetEvent = "DataVarSetEvent", + StacksDataMapInsertEvent = "DataMapInsertEvent", + StacksDataMapUpdateEvent = "DataMapUpdateEvent", + StacksDataMapDeleteEvent = "DataMapDeleteEvent", + StacksSmartContractEvent = "SmartContractEvent", +} + +export interface StacksSTXTransferEventData { + sender: string; + recipient: string; + amount: string; + memo?: string; +} + +export interface StacksSTXMintEventData { + recipient: string; + amount: string; +} + +export interface StacksSTXLockEventData { + locked_amount: string; + unlock_height: string; + locked_address: string; +} + +export interface StacksSTXBurnEventData { + sender: string; + amount: string; +} + +export interface StacksNFTTransferEventData { + asset_class_identifier: string; + asset_identifier: string; + sender: string; + recipient: string; +} + +export interface StacksNFTMintEventData { + asset_class_identifier: string; + asset_identifier: string; + recipient: string; +} + +export interface StacksNFTBurnEventData { + asset_class_identifier: string; + asset_identifier: string; + sender: string; +} + +export interface StacksFTTransferEventData { + asset_identifier: string; + sender: string; + recipient: string; + amount: string; +} + +export interface StacksFTMintEventData { + asset_identifier: string; + recipient: string; + amount: string; +} + +export interface StacksFTBurnEventData { + asset_identifier: string; + sender: string; + amount: string; +} + +export interface StacksDataVarSetEventData { + contract_identifier: string; + var: string; + new_value: string; +} + +export interface StacksDataMapInsertEventData { + contract_identifier: String; + map: string; + inserted_key: string; + inserted_value: string; +} + +export interface StacksDataMapUpdateEventData { + contract_identifier: string; + map: string; + key: string; + new_value: string; +} + +export interface StacksDataMapDeleteEventData { + contract_identifier: string; + map: string; + deleted_key: string; +} + +export interface StacksSmartContractEventData { + contract_identifier: string; + topic: string; + value: string; +} + +/** + * BitcoinTransactionMetadata contain an specific data about Bitcoin transactions. + * @export + * @interface BitcoinTransactionMetadata + */ +export interface BitcoinTransactionMetadata { + inputs: Input[]; + outputs: Output[]; + /** + * @type {string} + * @memberof StacksTransactionMetadata + */ + proof?: string; +} + +export interface Input { + previous_output: string; + script_sig: string; + sequence: number; + witness: any[]; +} + +export interface Output { + value: number; + script_pubkey: string; +} + +/** + * StacksTransaction contain an array of Operations that are attributable to the same TransactionIdentifier. + * @export + * @interface StacksTransaction + */ +export interface StacksTransaction { + /** + * @type {TransactionIdentifier} + * @memberof Transaction + */ + transaction_identifier: TransactionIdentifier; + /** + * @type {Array} + * @memberof Transaction + */ + operations: Array; + /** + * @type {Array} + * @memberof Transaction + */ + related_transactions?: Array; + /** + * Transactions that are related to other transactions (like a cross-shard transaction) should include the tranaction_identifier of these transactions in the metadata. + * @type {object} + * @memberof StacksTransactionMetadata + */ + metadata: StacksTransactionMetadata; +} + +/** + * BitcoinTransaction contain an array of Operations that are attributable to the same TransactionIdentifier. + * @export + * @interface BitcoinTransaction + */ +export interface BitcoinTransaction { + /** + * @type {TransactionIdentifier} + * @memberof Transaction + */ + transaction_identifier: TransactionIdentifier; + /** + * @type {Array} + * @memberof Transaction + */ + operations: Array; + /** + * @type {Array} + * @memberof Transaction + */ + related_transactions?: Array; + /** + * Transactions that are related to other transactions (like a cross-shard transaction) should include the tranaction_identifier of these transactions in the metadata. + * @type {object} + * @memberof BitcoinTransactionMetadata + */ + metadata: BitcoinTransactionMetadata; +} + +/** + * Transactions contain an array of Operations that are attributable to the same TransactionIdentifier. + * @export + * @interface Transaction + */ +export interface Transaction { + /** + * @type {TransactionIdentifier} + * @memberof Transaction + */ + transaction_identifier: TransactionIdentifier; + /** + * @type {Array} + * @memberof Transaction + */ + operations: Array; + /** + * @type {Array} + * @memberof Transaction + */ + related_transactions?: Array; + /** + * Transactions that are related to other transactions (like a cross-shard transaction) should include the tranaction_identifier of these transactions in the metadata. + * @type {object} + * @memberof Transaction + */ + metadata?: StacksTransactionMetadata | BitcoinTransactionMetadata; +} + +/** + * StacksBlockMetadata contains specific data about Stacks blocks. + * @export + * @interface StacksBlockMetadata + */ +export interface StacksBlockMetadata { + /** + * @type {BlockIdentifier} + * @memberof StacksBlockMetadata + */ + bitcoin_anchor_block_identifier: BlockIdentifier; + /** + * @type {BlockIdentifier} + * @memberof StacksBlockMetadata + */ + confirm_microblock_identifier?: BlockIdentifier; + /** + * @type {number} + * @memberof StacksBlockMetadata + */ + pox_cycle_index: number; + /** + * @type {number} + * @memberof StacksBlockMetadata + */ + pox_cycle_position: number; + /** + * @type {number} + * @memberof StacksBlockMetadata + */ + pox_cycle_length: number; +} + +/** + * BitcoinBlockMetadata contains specific data about Bitcoin blocks. + * @export + * @interface BitcoinBlockMetadata + */ +export interface BitcoinBlockMetadata {} + +/** + * The block_identifier uniquely identifies a block in a particular network. + * @export + * @interface BlockIdentifier + */ +export interface BlockIdentifier { + /** + * This is also known as the block height. + * @type {number} + * @memberof BlockIdentifier + */ + index: number; + /** + * @type {string} + * @memberof BlockIdentifier + */ + hash: string; +} + +/** + * Blocks contain an array of Transactions that occurred at a particular BlockIdentifier. A hard requirement for blocks returned by Rosetta implementations is that they MUST be _inalterable_: once a client has requested and received a block identified by a specific BlockIndentifier, all future calls for that same BlockIdentifier must return the same block contents. + * @export + * @interface Block + */ +export interface Block { + /** + * @type {BlockIdentifier} + * @memberof Block + */ + block_identifier: BlockIdentifier; + /** + * @type {BlockIdentifier} + * @memberof Block + */ + parent_block_identifier: BlockIdentifier; + /** + * The timestamp of the block in milliseconds since the Unix Epoch. The timestamp is stored in milliseconds because some blockchains produce blocks more often than once a second. + * @type {number} + * @memberof Block + */ + timestamp: number; + /** + * @type {Array} + * @memberof Block + */ + transactions: Array; + /** + * @type {object} + * @memberof Block + */ + metadata?: StacksBlockMetadata | BitcoinBlockMetadata; +} + +/** + * The operation_identifier uniquely identifies an operation within a transaction. + * @export + * @interface OperationIdentifier + */ +export interface OperationIdentifier { + /** + * The operation index is used to ensure each operation has a unique identifier within a transaction. This index is only relative to the transaction and NOT GLOBAL. The operations in each transaction should start from index 0. To clarify, there may not be any notion of an operation index in the blockchain being described. + * @type {number} + * @memberof OperationIdentifier + */ + index: number; + /** + * Some blockchains specify an operation index that is essential for client use. For example, Bitcoin uses a network_index to identify which UTXO was used in a transaction. network_index should not be populated if there is no notion of an operation index in a blockchain (typically most account-based blockchains). + * @type {number} + * @memberof OperationIdentifier + */ + network_index?: number; +} + +/** + * The account_identifier uniquely identifies an account within a network. All fields in the account_identifier are utilized to determine this uniqueness (including the metadata field, if populated). + * @export + * @interface AccountIdentifier + */ +export interface AccountIdentifier { + /** + * The address may be a cryptographic public key (or some encoding of it) or a provided username. + * @type {string} + * @memberof AccountIdentifier + */ + address: string; + /** + * @type {SubAccountIdentifier} + * @memberof AccountIdentifier + */ + sub_account?: SubAccountIdentifier; + /** + * Blockchains that utilize a username model (where the address is not a derivative of a cryptographic public key) should specify the public key(s) owned by the address in metadata. + * @type {object} + * @memberof AccountIdentifier + */ + metadata?: object; +} + +/** + * An account may have state specific to a contract address (SIP-10 token) and/or a stake (delegated balance). The sub_account_identifier should specify which state (if applicable) an account instantiation refers to. + * @export + * @interface SubAccountIdentifier + */ +export interface SubAccountIdentifier { + /** + * The SubAccount address may be a cryptographic value or some other identifier (ex: bonded) that uniquely specifies a SubAccount. + * @type {string} + * @memberof SubAccountIdentifier + */ + address: string; + /** + * If the SubAccount address is not sufficient to uniquely specify a SubAccount, any other identifying information can be stored here. It is important to note that two SubAccounts with identical addresses but differing metadata will not be considered equal by clients. + * @type {object} + * @memberof SubAccountIdentifier + */ + metadata?: object; +} + +/** + * Operations contain all balance-changing information within a transaction. They are always one-sided (only affect 1 AccountIdentifier) and can succeed or fail independently from a Transaction. Operations are used both to represent on-chain data (Data API) and to construct new transactions (Construction API), creating a standard interface for reading and writing to blockchains. + * @export + * @interface Operation + */ +export interface Operation { + /** + * @type {OperationIdentifier} + * @memberof Operation + */ + operation_identifier: OperationIdentifier; + /** + * Restrict referenced related_operations to identifier indices < the current operation_identifier.index. This ensures there exists a clear DAG-structure of relations. Since operations are one-sided, one could imagine relating operations in a single transfer or linking operations in a call tree. + * @type {Array} + * @memberof Operation + */ + related_operations?: Array; + /** + * Type is the network-specific type of the operation. Ensure that any type that can be returned here is also specified in the NetworkOptionsResponse. This can be very useful to downstream consumers that parse all block data. + * @type {string} + * @memberof Operation + */ + type: string; + /** + * Status is the network-specific status of the operation. Status is not defined on the transaction object because blockchains with smart contracts may have transactions that partially apply (some operations are successful and some are not). Blockchains with atomic transactions (all operations succeed or all operations fail) will have the same status for each operation. On-chain operations (operations retrieved in the `/block` and `/block/transaction` endpoints) MUST have a populated status field (anything on-chain must have succeeded or failed). However, operations provided during transaction construction (often times called "intent" in the documentation) MUST NOT have a populated status field (operations yet to be included on-chain have not yet succeeded or failed). + * @type {string} + * @memberof Operation + */ + status?: string; + /** + * @type {AccountIdentifier} + * @memberof Operation + */ + account?: AccountIdentifier; + /** + * @type {Amount} + * @memberof Operation + */ + amount?: Amount; + /** + * @type {CoinChange} + * @memberof Operation + */ + coin_change?: CoinChange; + /** + * @type {object} + * @memberof Operation + */ + metadata?: object; +} + +/** + * Amount is some Value of a Currency. It is considered invalid to specify a Value without a Currency. + * @export + * @interface Amount + */ +export interface Amount { + /** + * Value of the transaction in atomic units represented as an arbitrary-sized signed integer. For example, 1 BTC would be represented by a value of 100000000. + * @type {string} + * @memberof Amount + */ + value: string; + /** + * @type {Currency} + * @memberof Amount + */ + currency: Currency; + /** + * @type {object} + * @memberof Amount + */ + metadata?: object; +} + +/** + * Currency is composed of a canonical Symbol and Decimals. This Decimals value is used to convert an Amount.Value from atomic units (Satoshis) to standard units (Bitcoins). + * @export + * @interface Currency + */ +export interface Currency { + /** + * Canonical symbol associated with a currency. + * @type {string} + * @memberof Currency + */ + symbol: string; + /** + * Number of decimal places in the standard unit representation of the amount. For example, BTC has 8 decimals. Note that it is not possible to represent the value of some currency in atomic units that is not base 10. + * @type {number} + * @memberof Currency + */ + decimals: number; + /** + * Any additional information related to the currency itself. For example, it would be useful to populate this object with the contract address of an SIP-10 token. + * @type {object} + * @memberof Currency + */ + metadata?: object; +} + +/** + * CoinIdentifier uniquely identifies a Coin. + * @export + * @interface CoinIdentifier + */ +export interface CoinIdentifier { + /** + * Identifier should be populated with a globally unique identifier of a Coin. In Bitcoin, this identifier would be transaction_hash:index. + * @type {string} + * @memberof CoinIdentifier + */ + identifier: string; +} + +/** + * CoinChange is used to represent a change in state of a some coin identified by a coin_identifier. This object is part of the Operation model and must be populated for UTXO-based blockchains. Coincidentally, this abstraction of UTXOs allows for supporting both account-based transfers and UTXO-based transfers on the same blockchain (when a transfer is account-based, don't populate this model). + * @export + * @interface CoinChange + */ +export interface CoinChange { + /** + * @type {CoinIdentifier} + * @memberof CoinChange + */ + coin_identifier: CoinIdentifier; + /** + * @type {CoinAction} + * @memberof CoinChange + */ + coin_action: CoinAction; +} + +/** + * CoinActions are different state changes that a Coin can undergo. When a Coin is created, it is coin_created. When a Coin is spent, it is coin_spent. It is assumed that a single Coin cannot be created or spent more than once. + * @export + * @enum {string} + */ +export enum CoinAction { + created = "coin_created", + spent = "coin_spent", +} + +/** + * Contract interfaces are ABI returned by the stacks node + * @export + * @interface StacksContractInterface + */ +export interface StacksContractInterface { + /** + * List of defined methods + * @type {Array} + * @memberof ContractInterfaceResponse + */ + functions: Array; + /** + * List of defined variables + * @type {Array} + * @memberof ContractInterfaceResponse + */ + variables: Array; + /** + * List of defined data-maps + * @type {Array} + * @memberof ContractInterfaceResponse + */ + maps: Array; + /** + * List of fungible tokens in the contract + * @type {Array} + * @memberof ContractInterfaceResponse + */ + fungible_tokens: Array; + /** + * List of non-fungible tokens in the contract + * @type {Array} + * @memberof ContractInterfaceResponse + */ + non_fungible_tokens: Array; +} + +/** + * DataVarField describes clarity data-var metadata. + * @export + * @interface DataVarField + */ +export interface DataVarField { + /** + * Name of var + * @type {string} + * @memberof DataVarField + */ + name: string; +} + +/** + * DataMapField describes clarity data-map metadata. + * @export + * @interface DataMapField + */ +export interface DataMapField { + /** + * Name of map + * @type {string} + * @memberof DataMapField + */ + name: string; +} + +/** + * DataMapField describes clarity fungible token metadata. + * @export + * @interface DataFtField + */ +export interface DataFtField { + /** + * Name of fungible token + * @type {string} + * @memberof DataFtField + */ + name: string; +} + +/** + * DataMapField describes clarity non fungible token metadata. + * @export + * @interface DataNftField + */ +export interface DataNftField { + /** + * Name of non fungible token + * @type {string} + * @memberof DataNftField + */ + name: string; +} + +export function checkBitcoinProof( + txid: string, + blockHash: string, + merkleProof: string[], + index: number +): boolean { + +} + +// I'll add some documentation, but this is a "standard" bitcoin proof, so it goes as follow: +// So for instance, you'll receive something like this: +// 00000020662e181f6a5a6a32c617557b8b99665766fb6d30894b8c6dc95ae7a5541fec3094a49ed1f0c4f64d062e21786e9b31d2a0a4422488fe524f732f91e88ed0eff8f96c4d63ffff7f200100000003000000022e170a1c679957090bcec6fe4a528df8f6fe41ccb453f287607ddb82329991f0381610a752745bf85071d66f1b3559f7168ea05495e983dc8 +// Wire format: +// 1) 80 bytes: Block header (00000020662e181f6a5a6a32c617557b8b99665766fb6d30894b8c6dc95ae7a5541fec3094a49ed1f0c4f64d062e21786e9b31d2a0a4422488fe524f732f91e88ed0eff8f96c4d63ffff7f2001000000) +// 2) 4 bytes: Number of transaction in the block, little endian: (03000000) +// 3) Number of hashes (varint, 1 - 3 bytes): 02 +// 4) Hashes (N * 32 bytes, little endian) +// - 2e170a1c679957090bcec6fe4a528df8f6fe41ccb453f287607ddb82329991f0 +// - 381610a752745bf85071d66f1b3559f7168ea05495e983dc80e764e6b744006a +// 5) Number of bytes of flag bits (varint, 1 - 3 bytes) - 01 +// 6) Flag bits (little endian) - 0d + +// Flag bits indicate which nodes in the merkle tree are relevant for the proof (depth-first). Hashes are also listed in a depth-first fashion. This is relevant for proofs that cover more than one transaction. diff --git a/components/chainhook-types-js/tsconfig.json b/components/chainhook-types-js/tsconfig.json new file mode 100644 index 0000000..c152e45 --- /dev/null +++ b/components/chainhook-types-js/tsconfig.json @@ -0,0 +1,100 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Projects */ + // "incremental": true, /* Enable incremental compilation */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ + // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "resolveJsonModule": true, /* Enable importing .json files */ + // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ + // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ + // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true, /* Skip type checking all .d.ts files. */ + } +} diff --git a/components/chainhook-types-rs/Cargo.toml b/components/chainhook-types-rs/Cargo.toml new file mode 100644 index 0000000..c086faf --- /dev/null +++ b/components/chainhook-types-rs/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "chainhook-types" +version = "1.0.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde = "1" +serde_json = "1" +serde_derive = "1" +strum = { version = "0.23.0", features = ["derive"] } +schemars = { version = "0.8.10" } diff --git a/components/chainhook-types-rs/src/bitcoin.rs b/components/chainhook-types-rs/src/bitcoin.rs new file mode 100644 index 0000000..dc5cc2c --- /dev/null +++ b/components/chainhook-types-rs/src/bitcoin.rs @@ -0,0 +1,66 @@ +/// A transaction input, which defines old coins to be consumed +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Serialize, Deserialize)] +pub struct TxIn { + /// The reference to the previous output that is being used an an input. + pub previous_output: OutPoint, + /// The script which pushes values on the stack which will cause + /// the referenced output's script to be accepted. + pub script_sig: String, + /// The sequence number, which suggests to miners which of two + /// conflicting transactions should be preferred, or 0xFFFFFFFF + /// to ignore this feature. This is generally never used since + /// the miner behaviour cannot be enforced. + pub sequence: u32, + /// Witness data: an array of byte-arrays. + /// Note that this field is *not* (de)serialized with the rest of the TxIn in + /// Encodable/Decodable, as it is (de)serialized at the end of the full + /// Transaction. It *is* (de)serialized with the rest of the TxIn in other + /// (de)serialization routines. + pub witness: Vec, +} + +/// A transaction output, which defines new coins to be created from old ones. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Serialize, Deserialize)] +pub struct TxOut { + /// The value of the output, in satoshis. + pub value: u64, + /// The script which must be satisfied for the output to be spent. + pub script_pubkey: String, +} + +/// A reference to a transaction output. +#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct OutPoint { + /// The referenced transaction's txid. + pub txid: String, + /// The index of the referenced output in its transaction's vout. + pub vout: u32, +} + +/// The Witness is the data used to unlock bitcoins since the [segwit upgrade](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki) +/// +/// Can be logically seen as an array of byte-arrays `Vec>` and indeed you can convert from +/// it [`Witness::from_vec`] and convert into it [`Witness::to_vec`]. +/// +/// For serialization and deserialization performance it is stored internally as a single `Vec`, +/// saving some allocations. +/// +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash, Serialize, Deserialize)] +pub struct Witness { + /// contains the witness Vec> serialization without the initial varint indicating the + /// number of elements (which is stored in `witness_elements`) + content: Vec, + + /// Number of elements in the witness. + /// It is stored separately (instead of as VarInt in the initial part of content) so that method + /// like [`Witness::push`] doesn't have case requiring to shift the entire array + witness_elements: usize, + + /// If `witness_elements > 0` it's a valid index pointing to the last witness element in `content` + /// (Including the varint specifying the length of the element) + last: usize, + + /// If `witness_elements > 1` it's a valid index pointing to the second-to-last witness element in `content` + /// (Including the varint specifying the length of the element) + second_to_last: usize, +} diff --git a/components/chainhook-types-rs/src/events.rs b/components/chainhook-types-rs/src/events.rs new file mode 100644 index 0000000..c9a65cd --- /dev/null +++ b/components/chainhook-types-rs/src/events.rs @@ -0,0 +1,142 @@ +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct STXTransferEventData { + pub sender: String, + pub recipient: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct STXMintEventData { + pub recipient: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct STXLockEventData { + pub locked_amount: String, + pub unlock_height: String, + pub locked_address: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct STXBurnEventData { + pub sender: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct NFTTransferEventData { + #[serde(rename = "asset_identifier")] + pub asset_class_identifier: String, + #[serde(rename = "raw_value")] + pub hex_asset_identifier: String, + pub sender: String, + pub recipient: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct NFTMintEventData { + #[serde(rename = "asset_identifier")] + pub asset_class_identifier: String, + #[serde(rename = "raw_value")] + pub hex_asset_identifier: String, + pub recipient: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct NFTBurnEventData { + #[serde(rename = "asset_identifier")] + pub asset_class_identifier: String, + #[serde(rename = "raw_value")] + pub hex_asset_identifier: String, + pub sender: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct FTTransferEventData { + #[serde(rename = "asset_identifier")] + pub asset_class_identifier: String, + pub sender: String, + pub recipient: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct FTMintEventData { + #[serde(rename = "asset_identifier")] + pub asset_class_identifier: String, + pub recipient: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct FTBurnEventData { + #[serde(rename = "asset_identifier")] + pub asset_class_identifier: String, + pub sender: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct DataVarSetEventData { + pub contract_identifier: String, + pub var: String, + #[serde(rename = "raw_new_value")] + pub hex_new_value: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct DataMapInsertEventData { + pub contract_identifier: String, + pub map: String, + #[serde(rename = "raw_inserted_key")] + pub hex_inserted_key: String, + #[serde(rename = "raw_inserted_value")] + pub hex_inserted_value: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct DataMapUpdateEventData { + pub contract_identifier: String, + pub map: String, + #[serde(rename = "raw_key")] + pub hex_key: String, + #[serde(rename = "raw_new_value")] + pub hex_new_value: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct DataMapDeleteEventData { + pub contract_identifier: String, + pub map: String, + #[serde(rename = "raw_deleted_key")] + pub hex_deleted_key: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] +pub struct SmartContractEventData { + pub contract_identifier: String, + pub topic: String, + #[serde(rename = "raw_value")] + pub hex_value: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(tag = "type", content = "data")] +pub enum StacksTransactionEvent { + STXTransferEvent(STXTransferEventData), + STXMintEvent(STXMintEventData), + STXLockEvent(STXLockEventData), + STXBurnEvent(STXBurnEventData), + NFTTransferEvent(NFTTransferEventData), + NFTMintEvent(NFTMintEventData), + NFTBurnEvent(NFTBurnEventData), + FTTransferEvent(FTTransferEventData), + FTMintEvent(FTMintEventData), + FTBurnEvent(FTBurnEventData), + DataVarSetEvent(DataVarSetEventData), + DataMapInsertEvent(DataMapInsertEventData), + DataMapUpdateEvent(DataMapUpdateEventData), + DataMapDeleteEvent(DataMapDeleteEventData), + SmartContractEvent(SmartContractEventData), +} diff --git a/components/chainhook-types-rs/src/lib.rs b/components/chainhook-types-rs/src/lib.rs new file mode 100644 index 0000000..38defb8 --- /dev/null +++ b/components/chainhook-types-rs/src/lib.rs @@ -0,0 +1,16 @@ +extern crate serde; + +#[macro_use] +extern crate serde_derive; + +pub mod bitcoin; +mod events; +mod rosetta; + +pub use events::*; +pub use rosetta::*; + +pub enum Chain { + Bitcoin, + Stacks, +} diff --git a/components/chainhook-types-rs/src/proto/messages.proto b/components/chainhook-types-rs/src/proto/messages.proto new file mode 100644 index 0000000..4090716 --- /dev/null +++ b/components/chainhook-types-rs/src/proto/messages.proto @@ -0,0 +1,94 @@ +syntax = "proto3"; + +package chainhook.messages; + +// The ProtocolStateStreamer service definition. +service ChainStateStreamer { + // Get Bitcoin chain tip + rpc GetBitcoinChainTip(None) returns (BitcoinBlockData); +} + +message None {} + +message Chain { + oneof network { + BitcoinChain bitcoin = 1; + StacksChain stacks = 2; + } +} + +enum BitcoinChain { + BITCOIN_REGTEST = 0; + BITCOIN_TESTNET = 1; + BITCOIN_MAINNET = 2; + // BITCOIN_SIGNET = 3; +} + +enum StacksChain { + STACKS_DEVNET = 0; + STACKS_TESTNET = 1; + STACKS_MAINNET = 2; +} + +/// BlockIdentifier uniquely identifies a block in a particular network. +message BlockIdentifier { + /// Also known as the block height. + uint64 index = 1; + string hash = 2; +} + +/// The transaction_identifier uniquely identifies a transaction in a particular +/// network and block or in the mempool. +message TransactionIdentifier { + /// Any transactions that are attributable only to a block (ex: a block + /// event) should use the hash of the block as the identifier. + string hash = 1; +} + +message BitcoinChainUpdate { + oneof bitcoin_chain_event { + ChainUpdatedWithBlockData chain_updated_with_block = 1; + StacksChainUpdatedWithReorgData chain_updated_with_reorg = 2; + } +} + +message ChainUpdatedWithBlockData { + BitcoinBlockData new_block = 1; +} + +message StacksChainUpdatedWithReorgData { + repeated BitcoinBlockData old_blocks = 1; + repeated BitcoinBlockData new_blocks = 2; +} + +message BitcoinBlockData { + BlockIdentifier block_identifier = 1; + BlockIdentifier parent_block_identifier = 2; + /// The timestamp of the block in milliseconds since the Unix Epoch. The + /// timestamp is stored in milliseconds because some blockchains produce + /// blocks more often than once a second. + uint64 timestamp = 3; + repeated BitcoinTransactionData transactions = 4; + BitcoinBlockMetadata metadata = 5; +} + +/// Transactions contain an array of Operations that are attributable to the +/// same TransactionIdentifier. +message BitcoinTransactionData { + TransactionIdentifier transaction_identifier = 1; + repeated BitcoinOperation operations = 2; + /// Transactions that are related to other transactions should include the + /// transaction_identifier of these transactions in the metadata. + BitcoinTransactionMetadata metadata = 3; +} + +message BitcoinOperation { +} + +message BitcoinBlockMetadata { + repeated string inputs = 1; + repeated string outputs = 2; +} + +message BitcoinTransactionMetadata { +} diff --git a/components/chainhook-types-rs/src/rosetta.rs b/components/chainhook-types-rs/src/rosetta.rs new file mode 100644 index 0000000..061793c --- /dev/null +++ b/components/chainhook-types-rs/src/rosetta.rs @@ -0,0 +1,700 @@ +use super::bitcoin::{TxIn, TxOut}; +use crate::events::*; +use schemars::JsonSchema; +use std::cmp::Ordering; +use std::collections::HashSet; +use std::fmt::Display; +use std::hash::{Hash, Hasher}; + +/// BlockIdentifier uniquely identifies a block in a particular network. +#[derive(Debug, Clone, Deserialize, Serialize, Default)] +pub struct BlockIdentifier { + /// Also known as the block height. + pub index: u64, + pub hash: String, +} + +impl Display for BlockIdentifier { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!( + f, + "Block #{} ({}...{})", + self.index, + &self.hash.as_str()[0..6], + &self.hash.as_str()[62..] + ) + } +} + +impl Hash for BlockIdentifier { + fn hash(&self, state: &mut H) { + self.hash.hash(state); + } +} + +impl Ord for BlockIdentifier { + fn cmp(&self, other: &Self) -> Ordering { + (other.index, &other.hash).cmp(&(self.index, &self.hash)) + } +} + +impl PartialOrd for BlockIdentifier { + fn partial_cmp(&self, other: &Self) -> Option { + Some(other.cmp(self)) + } +} + +impl PartialEq for BlockIdentifier { + fn eq(&self, other: &Self) -> bool { + self.hash == other.hash + } +} + +impl Eq for BlockIdentifier {} + +/// StacksBlock contain an array of Transactions that occurred at a particular +/// BlockIdentifier. A hard requirement for blocks returned by Rosetta +/// implementations is that they MUST be _inalterable_: once a client has +/// requested and received a block identified by a specific BlockIndentifier, +/// all future calls for that same BlockIdentifier must return the same block +/// contents. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksBlockData { + pub block_identifier: BlockIdentifier, + pub parent_block_identifier: BlockIdentifier, + /// The timestamp of the block in milliseconds since the Unix Epoch. The + /// timestamp is stored in milliseconds because some blockchains produce + /// blocks more often than once a second. + pub timestamp: i64, + pub transactions: Vec, + pub metadata: StacksBlockMetadata, +} + +/// StacksMicroblock contain an array of Transactions that occurred at a particular +/// BlockIdentifier. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksMicroblockData { + pub block_identifier: BlockIdentifier, + pub parent_block_identifier: BlockIdentifier, + /// The timestamp of the block in milliseconds since the Unix Epoch. The + /// timestamp is stored in milliseconds because some blockchains produce + /// blocks more often than once a second. + pub timestamp: i64, + pub transactions: Vec, + pub metadata: StacksMicroblockMetadata, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksMicroblockMetadata { + pub anchor_block_identifier: BlockIdentifier, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksMicroblocksTrail { + pub microblocks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksBlockMetadata { + pub bitcoin_anchor_block_identifier: BlockIdentifier, + pub pox_cycle_index: u32, + pub pox_cycle_position: u32, + pub pox_cycle_length: u32, + pub confirm_microblock_identifier: Option, +} + +/// BitcoinBlock contain an array of Transactions that occurred at a particular +/// BlockIdentifier. A hard requirement for blocks returned by Rosetta +/// implementations is that they MUST be _inalterable_: once a client has +/// requested and received a block identified by a specific BlockIndentifier, +/// all future calls for that same BlockIdentifier must return the same block +/// contents. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BitcoinBlockData { + pub block_identifier: BlockIdentifier, + pub parent_block_identifier: BlockIdentifier, + /// The timestamp of the block in milliseconds since the Unix Epoch. The + /// timestamp is stored in milliseconds because some blockchains produce + /// blocks more often than once a second. + pub timestamp: u32, + pub transactions: Vec, + pub metadata: BitcoinBlockMetadata, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BitcoinBlockMetadata {} + +/// The timestamp of the block in milliseconds since the Unix Epoch. The +/// timestamp is stored in milliseconds because some blockchains produce blocks +/// more often than once a second. +#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize)] +pub struct Timestamp(i64); + +/// Transactions contain an array of Operations that are attributable to the +/// same TransactionIdentifier. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksTransactionData { + pub transaction_identifier: TransactionIdentifier, + pub operations: Vec, + /// Transactions that are related to other transactions should include the + /// transaction_identifier of these transactions in the metadata. + pub metadata: StacksTransactionMetadata, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum StacksTransactionKind { + ContractCall(StacksContractCallData), + ContractDeployment(StacksContractDeploymentData), + NativeTokenTransfer, + Coinbase, + Other, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksContractCallData { + pub contract_identifier: String, + pub method: String, + pub args: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksContractDeploymentData { + pub contract_identifier: String, + pub code: String, +} + +/// Extra data for Transaction +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksTransactionMetadata { + pub success: bool, + pub raw_tx: String, + pub result: String, + pub sender: String, + pub nonce: u64, + pub fee: u64, + pub kind: StacksTransactionKind, + pub receipt: StacksTransactionReceipt, + pub description: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub sponsor: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub execution_cost: Option, + pub position: StacksTransactionPosition, + pub proof: Option, +} + +/// TODO +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +#[serde(untagged)] +pub enum StacksTransactionPosition { + AnchorBlock(AnchorBlockPosition), + MicroBlock(MicroBlockPosition), +} + +impl StacksTransactionPosition { + pub fn anchor_block(index: usize) -> StacksTransactionPosition { + StacksTransactionPosition::AnchorBlock(AnchorBlockPosition { index }) + } + + pub fn micro_block( + micro_block_identifier: BlockIdentifier, + index: usize, + ) -> StacksTransactionPosition { + StacksTransactionPosition::MicroBlock(MicroBlockPosition { + micro_block_identifier, + index, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct AnchorBlockPosition { + index: usize, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct MicroBlockPosition { + micro_block_identifier: BlockIdentifier, + index: usize, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct StacksTransactionExecutionCost { + pub write_length: u64, + pub write_count: u64, + pub read_length: u64, + pub read_count: u64, + pub runtime: u64, +} + +/// Extra event data for Transaction +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)] +pub struct StacksTransactionReceipt { + pub mutated_contracts_radius: HashSet, + pub mutated_assets_radius: HashSet, + pub contract_calls_stack: HashSet, + pub events: Vec, +} + +impl StacksTransactionReceipt { + pub fn new( + mutated_contracts_radius: HashSet, + mutated_assets_radius: HashSet, + events: Vec, + ) -> StacksTransactionReceipt { + StacksTransactionReceipt { + mutated_contracts_radius, + mutated_assets_radius, + contract_calls_stack: HashSet::new(), + events, + } + } +} + +/// Transactions contain an array of Operations that are attributable to the +/// same TransactionIdentifier. +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BitcoinTransactionData { + pub transaction_identifier: TransactionIdentifier, + pub operations: Vec, + /// Transactions that are related to other transactions should include the + /// transaction_identifier of these transactions in the metadata. + pub metadata: BitcoinTransactionMetadata, +} + +/// Extra data for Transaction +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BitcoinTransactionMetadata { + pub inputs: Vec, + pub outputs: Vec, + pub stacks_operations: Vec, + pub proof: Option, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub enum StacksBaseChainOperation { + PoxBlockCommitment(PoxBlockCommitmentData), + PobBlockCommitment(PobBlockCommitmentData), + KeyRegistration(KeyRegistrationData), + TransferSTX(TransferSTXData), + LockSTX(LockSTXData), +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PoxBlockCommitmentData { + pub signers: Vec, + pub stacks_block_hash: String, + pub rewards: Vec, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PoxReward { + pub recipient: String, + pub amount: u64, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct KeyRegistrationData; + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct PobBlockCommitmentData { + pub signers: Vec, + pub stacks_block_hash: String, + pub amount: u64, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct BlockCommitmentData { + pub stacks_block_hash: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct TransferSTXData { + pub sender: String, + pub recipient: String, + pub amount: String, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct LockSTXData { + pub sender: String, + pub amount: String, + pub duration: u64, +} + +/// The transaction_identifier uniquely identifies a transaction in a particular +/// network and block or in the mempool. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Hash)] +pub struct TransactionIdentifier { + /// Any transactions that are attributable only to a block (ex: a block + /// event) should use the hash of the block as the identifier. + pub hash: String, +} + +#[derive( + Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::EnumIter, strum::IntoStaticStr, +)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum OperationType { + Credit, + Debit, + Lock, +} + +#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)] +pub struct OperationMetadata { + /// Has to be specified for ADD_KEY, REMOVE_KEY, and STAKE operations + #[serde(skip_serializing_if = "Option::is_none")] + pub public_key: Option, + // TODO(lgalabru): ??? + //#[serde(skip_serializing_if = "Option::is_none")] + // pub access_key: Option, + /// Has to be specified for DEPLOY_CONTRACT operation + #[serde(skip_serializing_if = "Option::is_none")] + pub code: Option, + /// Has to be specified for FUNCTION_CALL operation + #[serde(skip_serializing_if = "Option::is_none")] + pub method_name: Option, + /// Has to be specified for FUNCTION_CALL operation + #[serde(skip_serializing_if = "Option::is_none")] + pub args: Option, +} + +/// PublicKey contains a public key byte array for a particular CurveType +/// encoded in hex. Note that there is no PrivateKey struct as this is NEVER the +/// concern of an implementation. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PublicKey { + /// Hex-encoded public key bytes in the format specified by the CurveType. + pub hex_bytes: Option, + pub curve_type: CurveType, +} + +/// CurveType is the type of cryptographic curve associated with a PublicKey. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CurveType { + /// `y (255-bits) || x-sign-bit (1-bit)` - `32 bytes` (https://ed25519.cr.yp.to/ed25519-20110926.pdf) + Edwards25519, + /// SEC compressed - `33 bytes` (https://secg.org/sec1-v2.pdf#subsubsection.2.3.3) + Secp256k1, +} + +/// Operations contain all balance-changing information within a transaction. +/// They are always one-sided (only affect 1 AccountIdentifier) and can +/// succeed or fail independently from a Transaction. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Operation { + pub operation_identifier: OperationIdentifier, + + /// Restrict referenced related_operations to identifier indexes < the + /// current operation_identifier.index. This ensures there exists a clear + /// DAG-structure of relations. Since operations are one-sided, one could + /// imagine relating operations in a single transfer or linking operations + /// in a call tree. + #[serde(skip_serializing_if = "Option::is_none")] + pub related_operations: Option>, + + /// The network-specific type of the operation. Ensure that any type that + /// can be returned here is also specified in the NetworkStatus. This can + /// be very useful to downstream consumers that parse all block data. + #[serde(rename = "type")] + pub type_: OperationType, + + /// The network-specific status of the operation. Status is not defined on + /// the transaction object because blockchains with smart contracts may have + /// transactions that partially apply. Blockchains with atomic transactions + /// (all operations succeed or all operations fail) will have the same + /// status for each operation. + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + + pub account: AccountIdentifier, + + #[serde(skip_serializing_if = "Option::is_none")] + pub amount: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +/// The operation_identifier uniquely identifies an operation within a +/// transaction. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct OperationIdentifier { + /// The operation index is used to ensure each operation has a unique + /// identifier within a transaction. This index is only relative to the + /// transaction and NOT GLOBAL. The operations in each transaction should + /// start from index 0. To clarify, there may not be any notion of an + /// operation index in the blockchain being described. + pub index: u32, + + /// Some blockchains specify an operation index that is essential for + /// client use. For example, Bitcoin uses a network_index to identify + /// which UTXO was used in a transaction. network_index should not be + /// populated if there is no notion of an operation index in a blockchain + /// (typically most account-based blockchains). + #[serde(skip_serializing_if = "Option::is_none")] + pub network_index: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, strum::EnumIter)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum OperationStatusKind { + Success, +} + +/// The account_identifier uniquely identifies an account within a network. All +/// fields in the account_identifier are utilized to determine this uniqueness +/// (including the metadata field, if populated). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct AccountIdentifier { + /// The address may be a cryptographic public key (or some encoding of it) + /// or a provided username. + pub address: String, + + #[serde(skip_serializing_if = "Option::is_none")] + pub sub_account: Option, + /* Rosetta Spec also optionally provides: + * + * /// Blockchains that utilize a username model (where the address is not a + * /// derivative of a cryptographic public key) should specify the public + * /// key(s) owned by the address in metadata. + * #[serde(skip_serializing_if = "Option::is_none")] + * pub metadata: Option, */ +} + +/// An account may have state specific to a contract address (ERC-20 token) +/// and/or a stake (delegated balance). The sub_account_identifier should +/// specify which state (if applicable) an account instantiation refers to. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct SubAccountIdentifier { + /// The SubAccount address may be a cryptographic value or some other + /// identifier (ex: bonded) that uniquely specifies a SubAccount. + pub address: SubAccount, + /* Rosetta Spec also optionally provides: + * + * /// If the SubAccount address is not sufficient to uniquely specify a + * /// SubAccount, any other identifying information can be stored here. It is + * /// important to note that two SubAccounts with identical addresses but + * /// differing metadata will not be considered equal by clients. + * #[serde(skip_serializing_if = "Option::is_none")] + * pub metadata: Option, */ +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum SubAccount { + LiquidBalanceForStorage, + Locked, +} + +/// Amount is some Value of a Currency. It is considered invalid to specify a +/// Value without a Currency. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Amount { + /// Value of the transaction in atomic units represented as an + /// arbitrary-sized signed integer. For example, 1 BTC would be represented + /// by a value of 100000000. + pub value: u128, + + pub currency: Currency, + /* Rosetta Spec also optionally provides: + * + * #[serde(skip_serializing_if = "Option::is_none")] + * pub metadata: Option, */ +} + +/// Currency is composed of a canonical Symbol and Decimals. This Decimals value +/// is used to convert an Amount.Value from atomic units (Satoshis) to standard +/// units (Bitcoins). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Currency { + /// Canonical symbol associated with a currency. + pub symbol: String, + + /// Number of decimal places in the standard unit representation of the + /// amount. For example, BTC has 8 decimals. Note that it is not possible + /// to represent the value of some currency in atomic units that is not base + /// 10. + pub decimals: u32, + + /// Any additional information related to the currency itself. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum CurrencyStandard { + Sip09, + Sip10, + None, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CurrencyMetadata { + pub asset_class_identifier: String, + pub asset_identifier: Option, + pub standard: CurrencyStandard, +} + +#[allow(dead_code)] +#[derive(Debug, Clone, PartialEq, Serialize)] +pub enum BitcoinChainEvent { + ChainUpdatedWithBlocks(BitcoinChainUpdatedWithBlocksData), + ChainUpdatedWithReorg(BitcoinChainUpdatedWithReorgData), +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BitcoinChainUpdatedWithBlocksData { + pub new_blocks: Vec, + pub confirmed_blocks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BitcoinChainUpdatedWithReorgData { + pub blocks_to_rollback: Vec, + pub blocks_to_apply: Vec, + pub confirmed_blocks: Vec, +} + +#[allow(dead_code)] +#[derive(Debug, Clone, PartialEq, Serialize)] +pub enum StacksChainEvent { + ChainUpdatedWithBlocks(StacksChainUpdatedWithBlocksData), + ChainUpdatedWithReorg(StacksChainUpdatedWithReorgData), + ChainUpdatedWithMicroblocks(StacksChainUpdatedWithMicroblocksData), + ChainUpdatedWithMicroblocksReorg(StacksChainUpdatedWithMicroblocksReorgData), +} + +impl StacksChainEvent { + pub fn get_confirmed_blocks(self) -> Vec { + match self { + StacksChainEvent::ChainUpdatedWithBlocks(event) => event.confirmed_blocks, + StacksChainEvent::ChainUpdatedWithReorg(event) => event.confirmed_blocks, + _ => vec![], + } + } + + pub fn new_block(&self) -> Option<&StacksBlockData> { + match self { + StacksChainEvent::ChainUpdatedWithBlocks(event) => { + event.new_blocks.first().and_then(|b| Some(&b.block)) + } + _ => None, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StacksBlockUpdate { + pub block: StacksBlockData, + pub parent_microblocks_to_rollback: Vec, + pub parent_microblocks_to_apply: Vec, +} + +impl StacksBlockUpdate { + pub fn new(block: StacksBlockData) -> StacksBlockUpdate { + StacksBlockUpdate { + block, + parent_microblocks_to_rollback: vec![], + parent_microblocks_to_apply: vec![], + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StacksChainUpdatedWithBlocksData { + pub new_blocks: Vec, + pub confirmed_blocks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StacksChainUpdatedWithReorgData { + pub blocks_to_rollback: Vec, + pub blocks_to_apply: Vec, + pub confirmed_blocks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StacksChainUpdatedWithMicroblocksData { + pub new_microblocks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct StacksChainUpdatedWithMicroblocksReorgData { + pub microblocks_to_rollback: Vec, + pub microblocks_to_apply: Vec, +} + +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum StacksNetwork { + Simnet, + Devnet, + Testnet, + Mainnet, +} + +impl StacksNetwork { + pub fn is_simnet(&self) -> bool { + match self { + StacksNetwork::Simnet => true, + _ => false, + } + } + + pub fn is_testnet(&self) -> bool { + match self { + StacksNetwork::Testnet => true, + _ => false, + } + } + + pub fn either_devnet_or_testnet(&self) -> bool { + match self { + StacksNetwork::Devnet | StacksNetwork::Testnet => true, + _ => false, + } + } + + pub fn either_testnet_or_mainnet(&self) -> bool { + match self { + StacksNetwork::Mainnet | StacksNetwork::Testnet => true, + _ => false, + } + } + + pub fn is_devnet(&self) -> bool { + match self { + StacksNetwork::Devnet => true, + _ => false, + } + } + + pub fn is_mainnet(&self) -> bool { + match self { + StacksNetwork::Mainnet => true, + _ => false, + } + } + + pub fn get_networks(&self) -> (BitcoinNetwork, StacksNetwork) { + match &self { + StacksNetwork::Simnet => (BitcoinNetwork::Regtest, StacksNetwork::Simnet), + StacksNetwork::Devnet => (BitcoinNetwork::Testnet, StacksNetwork::Devnet), + StacksNetwork::Testnet => (BitcoinNetwork::Testnet, StacksNetwork::Testnet), + StacksNetwork::Mainnet => (BitcoinNetwork::Mainnet, StacksNetwork::Mainnet), + } + } +} + +#[allow(dead_code)] +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum BitcoinNetwork { + Regtest, + Testnet, + Mainnet, +} diff --git a/components/hiro-system-kit/Cargo.toml b/components/hiro-system-kit/Cargo.toml new file mode 100644 index 0000000..f5e01b8 --- /dev/null +++ b/components/hiro-system-kit/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "hiro-system-kit" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +futures = "0.3.12" +tokio = { version = "1.24", optional = true } +ansi_term = "0.12.1" +atty = "0.2.14" +lazy_static = "1.4.0" +slog = { version = "2.7.0", optional = true } +slog-json = { version = "2.6.1", optional = true } +slog-scope = { version = "4.4.0", optional = true } +slog-term = { version = "2.9.0", optional = true } +slog-async = { version = "2.7.0", optional = true } +slog-atomic = { version = "3.1.0", optional = true } + +[features] +default = ["tokio_helpers"] +tokio_helpers = ["tokio/full"] +log = [ + "slog", + "slog-json", + "slog-scope", + "slog-term", + "slog-async", + "slog-atomic", +] +debug = ["log", "slog/max_level_trace", "slog/release_max_level_debug"] +release = ["log", "slog/max_level_info", "slog/release_max_level_info"] diff --git a/components/hiro-system-kit/src/lib.rs b/components/hiro-system-kit/src/lib.rs new file mode 100644 index 0000000..d0d33fc --- /dev/null +++ b/components/hiro-system-kit/src/lib.rs @@ -0,0 +1,34 @@ +mod macros; + +#[cfg(feature = "tokio_helpers")] +mod tokio_helpers; + +#[cfg(feature = "tokio_helpers")] +pub use tokio_helpers::*; + +#[cfg(feature = "log")] +pub mod log; + +// #[cfg(feature = "log")] +// pub extern crate slog_scope; + +// #[cfg(feature = "log")] +// pub use slog_scope::*; + +#[cfg(feature = "log")] +pub extern crate slog; + +#[cfg(feature = "log")] +pub use slog::*; + +#[cfg(feature = "log")] +pub extern crate slog_term; + +#[cfg(feature = "log")] +pub extern crate slog_async; + +use std::thread::Builder; + +pub fn thread_named(name: &str) -> Builder { + Builder::new().name(name.to_string()) +} diff --git a/components/hiro-system-kit/src/log/mod.rs b/components/hiro-system-kit/src/log/mod.rs new file mode 100644 index 0000000..9a3b452 --- /dev/null +++ b/components/hiro-system-kit/src/log/mod.rs @@ -0,0 +1,25 @@ +use slog::{o, Drain, Logger}; +use slog_async; +use slog_atomic::AtomicSwitch; +use slog_scope::GlobalLoggerGuard; +use slog_term; +use std::sync::Mutex; + +pub fn setup_global_logger(logger: Logger) -> GlobalLoggerGuard { + slog_scope::set_global_logger(logger) +} + +pub fn setup_logger() -> Logger { + if cfg!(feature = "release") { + Logger::root( + Mutex::new(slog_json::Json::default(std::io::stderr())).map(slog::Fuse), + slog::o!(), + ) + } else { + let decorator = slog_term::TermDecorator::new().build(); + let drain = Mutex::new(slog_term::FullFormat::new(decorator).build()).fuse(); + let drain = slog_async::Async::new(drain).build().fuse(); + let drain = AtomicSwitch::new(drain); + Logger::root(drain.fuse(), o!()) + } +} diff --git a/components/hiro-system-kit/src/macros.rs b/components/hiro-system-kit/src/macros.rs new file mode 100644 index 0000000..f7da52f --- /dev/null +++ b/components/hiro-system-kit/src/macros.rs @@ -0,0 +1,167 @@ +#[allow(unused_macros)] +#[macro_export] +macro_rules! green { + ($($arg:tt)*) => ( + { + use atty::Stream; + use ansi_term::{Colour, Style}; + if atty::is(Stream::Stdout) { + let colour = Colour::Green.bold(); + format!( + "{}", + colour.paint($($arg)*) + ) + } else { + format!( + "{}", + $($arg)* + ) + } + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! red { + ($($arg:tt)*) => ( + { + use atty::Stream; + use ansi_term::{Colour, Style}; + if atty::is(Stream::Stdout) { + let colour = Colour::Red.bold(); + format!( + "{}", + colour.paint($($arg)*) + ) + } else { + format!( + "{}", + $($arg)* + ) + } + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! yellow { + ($($arg:tt)*) => ( + { + use atty::Stream; + use ansi_term::{Colour, Style}; + if atty::is(Stream::Stdout) { + let colour = Colour::Yellow.bold(); + format!( + "{}", + colour.paint($($arg)*) + ) + } else { + format!( + "{}", + $($arg)* + ) + } + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! blue { + ($($arg:tt)*) => ( + { + use atty::Stream; + use ansi_term::{Colour, Style}; + if atty::is(Stream::Stdout) { + let colour = Colour::Cyan.bold(); + format!( + "{}", + colour.paint($($arg)*) + ) + } else { + format!( + "{}", + $($arg)* + ) + } + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! purple { + ($($arg:tt)*) => ( + { + use atty::Stream; + use ansi_term::{Colour, Style}; + if atty::is(Stream::Stdout) { + let colour = Colour::Purple.bold(); + format!( + "{}", + colour.paint($($arg)*) + ) + } else { + format!( + "{}", + $($arg)* + ) + } + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! black { + ($($arg:tt)*) => ( + { + use atty::Stream; + use ansi_term::{Colour, Style}; + if atty::is(Stream::Stdout) { + let colour = Colour::Fixed(244); + format!( + "{}", + colour.paint($($arg)*) + ) + } else { + format!( + "{}", + $($arg)* + ) + } + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! format_err { + ($($arg:tt)*) => ( + { + format!("{} {}", red!("error:"), $($arg)*) + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! format_warn { + ($($arg:tt)*) => ( + { + format!("{} {}", yellow!("warn:"), $($arg)*) + } + ) +} + +#[allow(unused_macros)] +#[macro_export] +macro_rules! format_note { + ($($arg:tt)*) => ( + { + format!("{} {}", blue!("note:"), $($arg)*) + } + ) +} diff --git a/components/hiro-system-kit/src/tokio_helpers.rs b/components/hiro-system-kit/src/tokio_helpers.rs new file mode 100644 index 0000000..137a0f4 --- /dev/null +++ b/components/hiro-system-kit/src/tokio_helpers.rs @@ -0,0 +1,23 @@ +use std::future::Future; +use tokio; + +pub fn create_basic_runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_io() + .enable_time() + .max_blocking_threads(32) + .build() + .unwrap() +} + +pub fn nestable_block_on(future: F) -> F::Output { + let (handle, _rt) = match tokio::runtime::Handle::try_current() { + Ok(h) => (h, None), + Err(_) => { + let rt = tokio::runtime::Runtime::new().unwrap(); + (rt.handle().clone(), Some(rt)) + } + }; + let response = handle.block_on(async { future.await }); + response +} diff --git a/dockerfiles/components/chainhook-event-observer.dockerfile b/dockerfiles/components/chainhook-event-observer.dockerfile new file mode 100644 index 0000000..6096fa4 --- /dev/null +++ b/dockerfiles/components/chainhook-event-observer.dockerfile @@ -0,0 +1,37 @@ +FROM rust:bullseye as build + +WORKDIR /src + +RUN apt update && apt install -y ca-certificates pkg-config libssl-dev + +RUN rustup update 1.59.0 && rustup default 1.59.0 + +COPY ./components/chainhook-types-rs /src/components/chainhook-types-rs + +COPY ./components/chainhook-event-observer /src/components/chainhook-event-observer + +COPY ./components/stacks-rpc-client /src/components/stacks-rpc-client + +COPY ./components/clarity-repl /src/components/clarity-repl + +COPY ./components/clarinet-utils /src/components/clarinet-utils + +COPY ./components/hiro-system-kit /src/components/hiro-system-kit + +WORKDIR /src/components/chainhook-event-observer + +RUN mkdir /out + +RUN cargo build --release + +RUN cp target/release/chainhook-event-observer /out + +FROM debian:bullseye-slim + +RUN apt update && apt install -y libssl-dev + +COPY --from=build /out/ /bin/ + +WORKDIR /workspace + +ENTRYPOINT ["chainhook-event-observer"] \ No newline at end of file diff --git a/dockerfiles/components/chainhook-node.dockerfile b/dockerfiles/components/chainhook-node.dockerfile new file mode 100644 index 0000000..f8c0db1 --- /dev/null +++ b/dockerfiles/components/chainhook-node.dockerfile @@ -0,0 +1,39 @@ +FROM rust:bullseye as build + +WORKDIR /src + +RUN apt update && apt install -y ca-certificates pkg-config libssl-dev + +RUN rustup update 1.59.0 && rustup default 1.59.0 + +COPY ./components/chainhook-cli /src/components/chainhook-cli + +COPY ./components/chainhook-types-rs /src/components/chainhook-types-rs + +COPY ./components/chainhook-event-observer /src/components/chainhook-event-observer + +COPY ./components/stacks-rpc-client /src/components/stacks-rpc-client + +COPY ./components/clarity-repl /src/components/clarity-repl + +COPY ./components/clarinet-utils /src/components/clarinet-utils + +COPY ./components/hiro-system-kit /src/components/hiro-system-kit + +WORKDIR /src/components/chainhook-cli + +RUN mkdir /out + +RUN cargo build --features release --release + +RUN cp target/release/chainhook-cli /out + +FROM debian:bullseye-slim + +RUN apt update && apt install -y libssl-dev + +COPY --from=build /out/ /bin/ + +WORKDIR /workspace + +ENTRYPOINT ["chainhook-cli"] \ No newline at end of file diff --git a/rust-toolchain b/rust-toolchain new file mode 100644 index 0000000..05dfa32 --- /dev/null +++ b/rust-toolchain @@ -0,0 +1,2 @@ +[toolchain] +channel = "1.62.0" diff --git a/wix/License.rtf b/wix/License.rtf new file mode 100644 index 0000000..e63c94e --- /dev/null +++ b/wix/License.rtf @@ -0,0 +1,180 @@ +{\rtf1\ansi\deff0\nouicompat{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Courier New;}} +{\colortbl ;\red0\green0\blue255;} +{\*\generator Riched20 10.0.15063}\viewkind4\uc1 +\pard\sa180\qc\fs24\lang9 GNU GENERAL PUBLIC LICENSE\line Version 3, 29 June 2007\par + +\pard\sa180 Copyright (C) 2007 Free Software Foundation, Inc. {{\field{\*\fldinst{HYPERLINK http://fsf.org/ }}{\fldrslt{http://fsf.org/\ul0\cf0}}}}\f0\fs24 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\par + +\pard\sa180\qc Preamble\par + +\pard\sa180 The GNU General Public License is a free, copyleft license for software and other kinds of works.\par +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.\par +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.\par +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.\par +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.\par +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.\par +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.\par +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.\par +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.\par +The precise terms and conditions for copying, distribution and modification follow.\par + +\pard\sa180\qc TERMS AND CONDITIONS\par + +\pard\fi-360\li360\sa180\tx360 0.\tab Definitions.\par + +\pard\sa180 "This License" refers to version 3 of the GNU General Public License.\par +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\par +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.\par +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.\par +A "covered work" means either the unmodified Program or a work based on the Program.\par +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.\par +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.\par +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.\par + +\pard\fi-360\li360\sa180\tx360 1.\tab Source Code.\par + +\pard\sa180 The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.\par +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.\par +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.\par +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.\par +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\par +The Corresponding Source for a work in source code form is that same work.\par + +\pard\fi-360\li360\sa180\tx360 2.\tab Basic Permissions.\par + +\pard\sa180 All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.\par +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.\par +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\par + +\pard\fi-360\li360\sa180\tx360 3.\tab Protecting Users' Legal Rights From Anti-Circumvention Law.\par + +\pard\sa180 No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.\par +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.\par + +\pard\fi-360\li360\sa180\tx360 4.\tab Conveying Verbatim Copies.\par + +\pard\sa180 You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\par +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.\par + +\pard\fi-360\li360\sa180\tx360 5.\tab Conveying Modified Source Versions.\par + +\pard\sa180 You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:\par + +\pard +{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}} +\fi-360\li720\sa180 The work must carry prominent notices stating that you modified\lang1033 \lang9 it, and giving a relevant date.\par +{\pntext\f0 b.\tab}The work must carry prominent notices stating that it is released under this License and any conditions added under section\lang1033 \lang9 7.\lang1033 \lang9 This requirement modifies the requirement in section 4 to\lang1033 \lang9 "keep intact all notices".\par +{\pntext\f0 c.\tab}You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7\lang1033 \lang9 additional terms, to the whole of the work, and all its parts,\lang1033 \lang9 regardless of how they are packaged. This License gives no\lang1033 \lang9 permission to license the work in any other way, but it does not\lang1033 \lang9 invalidate such permission if you have separately received it. \par +{\pntext\f0 d.\tab}If the work has interactive user interfaces, each must display\lang1033 \lang9 Appropriate Legal Notices; however, if the Program has interactive\lang1033 \lang9 interfaces that do not display Appropriate Legal Notices, your\lang1033 \lang9 work need not make them do so.\par + +\pard\sa180 A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.\par + +\pard\fi-360\li360\sa180\tx360 6.\tab Conveying Non-Source Forms.\par + +\pard\sa180 You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:\par + +\pard +{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}} +\fi-360\li720\sa180 Convey the object code in, or embodied in, a physical product\line (including a physical distribution medium), accompanied by the\line Corresponding Source fixed on a durable physical medium\line customarily used for software interchange.\par +{\pntext\f0 b.\tab}Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no\line more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.\par +{\pntext\f0 c.\tab}Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.\par +{\pntext\f0 d.\tab}Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.\par +{\pntext\f0 e.\tab}Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.\par + +\pard\sa180 A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.\par +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.\par +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.\par +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).\par +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.\par +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.\par + +\pard\fi-360\li360\sa180\tx360 7.\tab Additional Terms.\par + +\pard\sa180 "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\par +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.\par +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:\par + +\pard +{\pntext\f0 a.\tab}{\*\pn\pnlvlbody\pnf0\pnindent0\pnstart1\pnlcltr{\pntxta.}} +\fi-360\li720\sa180 Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or\par +{\pntext\f0 b.\tab}Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or\par +{\pntext\f0 c.\tab}Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or\par +{\pntext\f0 d.\tab}Limiting the use for publicity purposes of names of licensors or authors of the material; or\par +{\pntext\f0 e.\tab}Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\par +{\pntext\f0 f.\tab}Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.\par + +\pard\sa180 All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.\par +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.\par +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.\par + +\pard\fi-360\li360\sa180\tx360 8.\tab Termination.\par + +\pard\sa180 You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).\par +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.\par +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.\par +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.\par + +\pard\fi-360\li360\sa180\tx360 9.\tab Acceptance Not Required for Having Copies.\par + +\pard\sa180 You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\par + +\pard\fi-360\li360\sa180\tx360 10.\tab Automatic Licensing of Downstream Recipients.\par + +\pard\sa180 Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.\par +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.\par +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\par + +\pard\fi-360\li360\sa180\tx360 11.\tab Patents.\par + +\pard\sa180 A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".\par +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\par +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.\par +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\par +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.\par +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.\par +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.\par +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.\par + +\pard\fi-360\li360\sa180\tx360 12.\tab No Surrender of Others' Freedom.\par + +\pard\sa180 If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.\par + +\pard\fi-360\li360\sa180\tx360 13.\tab Use with the GNU Affero General Public License.\par + +\pard\sa180 Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.\par + +\pard\fi-360\li360\sa180\tx360 14.\tab Revised Versions of this License.\par + +\pard\sa180 The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.\par +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.\par +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.\par +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.\par + +\pard\fi-360\li360\sa180\tx360 15.\tab Disclaimer of Warranty.\par + +\pard\sa180 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par + +\pard\fi-360\li360\sa180\tx360 16.\tab Limitation of Liability.\par + +\pard\sa180 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\par + +\pard\fi-360\li360\sa180\tx360 17.\tab Interpretation of Sections 15 and 16.\par + +\pard\sa180 If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.\par + +\pard\sa180\qc END OF TERMS AND CONDITIONS\par +\line How to Apply These Terms to Your New Programs\par + +\pard\sa180 If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.\par +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.\par +\f1 \line Copyright (C) [copyright-year] [copyright-holder]\par +\line This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\line\line This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\line\line You should have received a copy of the GNU General Public License along with this program. If not, see <{{\field{\*\fldinst{HYPERLINK "http://www.gnu.org/licenses/"}}{\fldrslt{http://www.gnu.org/licenses/\ul0\cf0}}}}\f1\fs24 >.\par +\f0 Also add information on how to contact you by electronic and paper mail.\par +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:\par +\f1 [product-name] Copyright (C) [copyright-year] [copyright-holder]\par +This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free software, and you are welcome to redistribute it under certain conditions; type 'show c' for details.\f0\par +The hypothetical commands {\f1 'show w'} and {\f1 'show c'} should show the appropriate arts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".\par +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see {{\field{\*\fldinst{HYPERLINK http://www.gnu.org/licenses/ }}{\fldrslt{http://www.gnu.org/licenses/\ul0\cf0}}}}\f0\fs24 .\par +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read {{\field{\*\fldinst{HYPERLINK http://www.gnu.org/philosophy/why-not-lgpl.html }}{\fldrslt{http://www.gnu.org/philosophy/why-not-lgpl.html\ul0\cf0}}}}\f0\fs24 .\par +} + diff --git a/wix/main.wxs b/wix/main.wxs new file mode 100644 index 0000000..2fccfea --- /dev/null +++ b/wix/main.wxs @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +