Fix wasm on-demand materialization file naming; set TLS SNI for forking gRPC#6
Open
Fix wasm on-demand materialization file naming; set TLS SNI for forking gRPC#6
Conversation
…AIN/0x.. -> CHAIN.ETH and CHAIN.0X.. for single GETs Co-Authored-By: francesco@bloctopus.io <ocsenarf@outlook.com>
…AIN/0x.. -> CHAIN.ETH and CHAIN.0X.. for single GETs Co-Authored-By: francesco@bloctopus.io <ocsenarf@outlook.com>
…rower) to avoid list failures Co-Authored-By: francesco@bloctopus.io <ocsenarf@outlook.com>
…rower) to avoid list failures Co-Authored-By: francesco@bloctopus.io <ocsenarf@outlook.com>
…case-insensitive address match Co-Authored-By: francesco@bloctopus.io <ocsenarf@outlook.com>
…case-insensitive address match Co-Authored-By: francesco@bloctopus.io <ocsenarf@outlook.com>
… pool asset before parsing
… pool asset before parsing
…/0X and case-insensitive match
…/0X and case-insensitive match
…er with {asset=**}; regenerate gateway/types
…er with {asset=**}; regenerate gateway/types
This allows mimir transactions to bypass all ante handlers including the SDK's DeductFeeDecorator, enabling them to work in test/forking environments where validators may not have unbonded funds.
This allows mimir transactions to bypass all ante handlers including the SDK's DeductFeeDecorator, enabling them to work in test/forking environments where validators may not have unbonded funds.
In forking mode, the bond module may have 0 balance. This change checks the bond module balance before attempting to transfer fees and skips the transfer if insufficient, allowing mimir transactions to succeed in test/forking environments.
In forking mode, the bond module may have 0 balance. This change checks the bond module balance before attempting to transfer fees and skips the transfer if insufficient, allowing mimir transactions to succeed in test/forking environments.
…authz integration
…authz integration
…kv-collision app: deduplicate KVStoreKeys to fix 'acc' collision after authz integration
…kv-collision app: deduplicate KVStoreKeys to fix 'acc' collision after authz integration
…minimal diagnostic to ensure WASMPERMISSIONLESS routing
…tantiate work without Mimir votes
… directly in forking mode; keep node vote and success logs
…n be validated against forked state
…N; no functional change
…w txs in forked mode
…CheckTx hangs when remote bank/auth reads fail
…ence query hangs in forking mode
…ccount/sequence; fix Mimir tx hang in forking
…id mempool hangs; rely on DeliverTx for remote
…nblock account/sequence; keep others blocked
…o unblock account/sequence in forking mode
…x hang when bypassing in forking mode
…rnode tx/query/keys can initialize with forking enabled
…or thornode tx/query
… (fix unknown flag on mimir)
…o appOpts in tx/query subcommands
…e ctx and retry; add bank client init
…nk-balances Disable remote reads for bank balances in forking mode
…t 10s timeout; always set user-api-call
…eight forwarding and user-api-call
…s; log invalid height param
…ance-hang fix: prevent REST bank balance hang in forking mode (gateway timeout + broader height forwarding)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
User description
Fix wasm on-demand materialization file naming; set TLS SNI for forking gRPC
Summary
This PR fixes the "Error opening Wasm file for reading" issue in forking mode by addressing two key problems:
Wasm file naming mismatch: Modified
materializeAndPinWasmto prefer the on-chainCodeHashfromCodeInfoinstead of always computing a local SHA256 hash, ensuring the generated filename matches what wasmvm expects during contract execution.TLS ServerName configuration: Added proper TLS configuration with
ServerNamefor gRPC connections to resolve connectivity issues when fetching wasm bytecode from remote endpoints.Key Changes
app/wasm_materialize.go: Use on-chain CodeHash for filename when available, write wasm files to multiple potential paths that wasmvm might checkapp/msg_wasm_wrapper.go&app/query_wasm_wrapper.go: Set TLS ServerName properly for gRPC dial optionsReview & Testing Checklist for Human
Critical (3 items):
grpc.thor.pfc.zone:443work properly with the new TLS ServerName configurationNotes
Testing was incomplete due to intermittent RPC EOF errors (
post failed: Post "http://localhost:26657": EOF) during verification. The materialization and pinning logs showed expected behavior, but full end-to-end contract execution could not be verified.The protobuf changes in
api/types/query.pulsar.goappear to be auto-generated and may need regeneration withmake generate.Link to Devin run: https://app.devin.ai/sessions/a93bebe179184ecfb0855343177bb0a7
Requested by: @tiljrd
PR Type
Enhancement, Bug fix, Documentation
Description
• Fixed WASM on-demand materialization: Modified
materializeAndPinWasmto use on-chainCodeHashfromCodeInfoinstead of computing local SHA256 hash, ensuring generated filenames match what wasmvm expects during contract execution• Added TLS ServerName configuration: Implemented proper TLS configuration with
ServerNamefor gRPC connections to resolve connectivity issues when fetching WASM bytecode from remote endpoints• Implemented comprehensive forking infrastructure: Added complete forking KV store system with remote gRPC client, LRU cache with TTL, iterator support, and proper state management
• Enhanced WASM contract handling: Created message and query wrappers to ensure automatic contract materialization before execution with fallback to remote endpoints
• Added authz module integration: Integrated authorization module with keeper initialization, store upgrades, and ante handler support
• Improved user API call detection: Added gRPC metadata extraction across handlers to identify user-initiated API calls for proper context propagation
• Enhanced query routing: Implemented custom query service router with route overrides and support for complex asset paths with slashes
• Added mimir bypass functionality: Implemented decorator to skip ante handlers for MsgMimir transactions and enhanced fee handling for forking scenarios
• Security improvements: Updated Docker build to use HTTPS repositories and improved CA certificate handling
Diagram Walkthrough
flowchart LR A["WASM Contract Request"] --> B["Message/Query Wrapper"] B --> C["Check Local Storage"] C --> D{Contract Available?} D -->|No| E["Remote gRPC Client"] E --> F["Fetch from Remote with TLS"] F --> G["Materialize & Pin WASM"] G --> H["Execute Contract"] D -->|Yes| H I["Forking KV Store"] --> J["Local Storage"] I --> K["LRU Cache"] I --> L["Remote Client"] M["User API Call"] --> N["gRPC Metadata"] N --> O["Context Propagation"]File Walkthrough
2 files
query.pb.go
Auto-generated protobuf file updatex/thorchain/types/query.pb.go
• Updated auto-generated protobuf file with new binary data
• Modified
gzipped FileDescriptorProto from 2646 to 2711 bytes
• Changed file
descriptor hash and content structure
query.pb.gw.go
Auto-generated gRPC gateway query handlers for alternative API routesx/thorchain/types/query.pb.gw.go
• Added duplicate query handler functions for LiquidityProvider,
LiquidityProviders, Saver, Savers, Borrower, and Borrowers endpoints
•
Added new URL patterns and forward response handlers for alternative
API routes
• Generated additional gRPC gateway code for query
endpoints with different path structures
27 files
iterator.go
New iterator implementations for forking mode data accessx/thorchain/forking/iterator.go
• Added
MergedIteratorstruct to merge local and remote iterators withproper key ordering
• Implemented
RemoteIteratorfor iterating overremote KeyValue slices
• Added
EmptyIteratoras a null iteratorimplementation
• Includes support for both forward and reverse
iteration modes
client.go
Complete forking gRPC client implementation with TLS supportx/thorchain/forking/client.go
• Implemented comprehensive remote gRPC client for forking mode with
TLS support
• Added WASM contract state fetching with proper key
parsing and address handling
• Implemented query methods for pools,
nodes, accounts, liquidity providers, savers, and borrowers
• Added
proper TLS configuration with
ServerNamefor secure gRPC connectionsmsg_thorchain_wrapper.go
WASM message wrapper with automatic code materializationapp/msg_thorchain_wrapper.go
• Created message wrapper for WASM contract operations with
materialization support
• Added automatic WASM code materialization
before contract instantiation and execution
• Implemented TLS-enabled
gRPC connection for fetching remote contract information
• Added
proper error handling and retry logic for height-based queries
msg_server.go
User API call detection via gRPC metadatax/denom/keeper/msg_server.go
• Added metadata extraction for user API call detection in all message
handlers
• Implemented context value setting for
CtxUserAPICallbasedon gRPC metadata
• Enhanced CreateDenom, MintTokens, BurnTokens, and
ChangeDenomAdmin methods
app.go
Add forking infrastructure and authz module integrationapp/app.go
• Added forking functionality with configuration for remote gRPC
connections and KV store services
• Integrated authz module with
keeper initialization and module registration
• Added wasm
materialization and query/message wrapper routing for forking mode
•
Implemented forking services initialization with cache and remote
client setup
query_wasm_wrapper.go
Implement WASM query wrapper with remote fallbackapp/query_wasm_wrapper.go
• Created WASM query wrapper to handle remote gRPC queries with TLS
configuration
• Implemented fallback logic to fetch contract data from
remote endpoints when not available locally
• Added proper TLS
ServerName configuration for secure gRPC connections
• Includes retry
logic for height-related errors and contract materialization
store.go
Core forking KV store implementationx/thorchain/forking/store.go
• Implemented forking KV store that checks local storage first, then
cache, then remote
• Added remote fetch logic with proper error
handling and caching
• Implemented iterator support for both forward
and reverse iteration with merged results
• Added debug logging and
statistics tracking for forking operations
msg_wasm_wrapper.go
Implement WASM message wrapper with materializationapp/msg_wasm_wrapper.go
• Created WASM message wrapper to ensure contract materialization
before execution
• Added TLS configuration for secure gRPC connections
to remote endpoints
• Implemented contract info fetching from remote
when not available locally
• Added proper error handling and retry
logic for remote queries
wasm_materialize.go
WASM bytecode materialization and pinning systemapp/wasm_materialize.go
• Implemented WASM bytecode materialization and pinning functionality
• Added remote bytecode fetching via gRPC with TLS support
• Created
multiple file path targets for WASM files to ensure compatibility
•
Added proper gzip decompression and SHA256 hash handling
msg_server_wasms.go
Add user API context to WASM message handlersx/thorchain/msg_server_wasms.go
• Added user API call context extraction from gRPC metadata for all
WASM message handlers
• Implemented proper context propagation for
forking mode detection
• Enhanced all WASM message server methods with
metadata handling
query_service_router.go
Custom query service router with context handlingapp/query_service_router.go
• Created custom query service router with route override capabilities
• Implemented bank query wrapper with user API call context extraction
• Added gRPC metadata handling for proper context propagation
•
Provided extensible framework for custom query handlers
cache.go
LRU cache implementation with TTL supportx/thorchain/forking/cache.go
• Implemented LRU cache with TTL support for forking data
• Added
thread-safe operations with proper mutex handling
• Included automatic
cleanup of expired entries
• Provided cache statistics and management
functionality
service.go
Forking KV store service implementationx/thorchain/forking/service.go
• Implemented forking KV store service wrapper with state management
•
Added block processing state tracking and genesis mode detection
•
Included statistics tracking for remote fetches and cache performance
• Provided proper service lifecycle management
ante.go
Mimir bypass decorator and authz supportx/thorchain/ante.go
• Added MimirBypassDecorator to skip ante handlers for MsgMimir
transactions
• Enhanced ante handler to support authz message types
•
Implemented early bypass logic with infinite gas meter for mimir
messages
querier.go
Enhanced pool query with contract address supportx/thorchain/querier.go
• Enhanced pool query to support contract address lookup with
case-insensitive matching
• Added support for both uppercase and
lowercase Ethereum address formats
• Implemented pool iteration to
find assets by contract address
types.go
Core forking types and interfacesx/thorchain/forking/types.go
• Defined core types and interfaces for forking functionality
•
Specified RemoteConfig, RemoteClient, Cache, and ForkingKVStore
interfaces
• Added statistics tracking and gas metering type
definitions
handler_wasm_execute_contract.go
Add authz support to WASM execute handlerx/thorchain/handler_wasm_execute_contract.go
• Added authz message types to WASM execute ante decorator
• Enhanced
fee handling to support authz grant, revoke, and exec messages
handler_send.go
Add user API context to send handlerx/thorchain/handler_send.go
• Added user API call context extraction from gRPC metadata
• Enhanced
bank send handler with proper context propagation
grpc_query.go
Add user API context to gRPC queriesx/thorchain/grpc_query.go
• Added user API call context extraction from gRPC metadata
• Enhanced
query server with proper context propagation for forking detection
msg_server.go
Add user API context to message serverx/thorchain/msg_server.go
• Added user API call context extraction from gRPC metadata to
external handler
• Enhanced message server with proper context
propagation
grpc_query.go
Add user API context to denom queriesx/denom/keeper/grpc_query.go
• Added user API call context extraction from gRPC metadata
• Enhanced
denom admin query with proper context propagation
upgrades.go
Add authz store to standard upgradesapp/upgrades/standard/upgrades.go
• Added authz store key to upgrade store additions
• Integrated authz
module into standard upgrade process
module.go
Add user API flag to gRPC gatewayx/thorchain/module.go
• Added user-api-call metadata flag to gRPC gateway router
• Enhanced
HTTP request handling with proper API call identification
ante.go
Add mimir bypass to ante handler chainapp/ante.go
• Added MimirBypassDecorator as first ante handler to bypass fee
deduction for mimir messages
gas.go
SDK gas meter wrapper implementationx/thorchain/forking/gas.go
• Implemented SDK gas meter wrapper for forking operations
• Added gas
consumption tracking and reporting functionality
query.proto
Enhanced protobuf routes for complex asset pathsproto/thorchain/v1/types/query.proto
• Updated HTTP route patterns to support asset paths with slashes
using
{asset=**}pattern• Added additional bindings for alternative
endpoint formats
• Enhanced API routing for complex asset identifiers
Dockerfile
Docker build security improvementsbuild/docker/Dockerfile
• Updated package installation to use HTTPS repositories
• Improved
security by copying CA certificates from build stage
• Enhanced Docker
build process with better practices
3 files
constants.go
New context key for user API call identificationconstants/constants.go
• Added new context key
CtxUserAPICallfor identifying user-initiatedAPI calls
flags.go
Forking module CLI flags configurationx/thorchain/forking/flags.go
• Added CLI flags for forking configuration including gRPC endpoint
and chain ID
• Implemented timeout, cache, and trust parameters for
remote connections
• Provided comprehensive configuration options for
forking behavior
commands.go
Add forking flags to thornode commandscmd/thornode/commands.go
• Added forking module initialization flags to start command
•
Integrated forking configuration with existing module setup
2 files
handler_mimir.go
Enhanced mimir handler for forking modex/thorchain/handler_mimir.go
• Modified mimir handler to skip fee deduction when bond module has
insufficient balance
• Added balance checking before attempting fee
transfers
• Improved error handling for forking mode scenarios
keeper_node_account.go
Fix typo in bond error messagex/thorchain/keeper/v1/keeper_node_account.go
• Fixed typo in error message from "not enound bond" to "not enough
bond"
1 files
README.md
Forking module documentationx/thorchain/forking/README.md
• Added comprehensive documentation for the forking module
•
Documented architecture, components, configuration, and usage
•
Provided testing guidelines and security considerations
1 files
go.mod
Update cosmos/evm dependencygo.mod
• Added replace directive for cosmos/evm dependency
1 files