Verona 백서

Verona

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 49쪽

at web and CLI clients interact with the blockchain. They make a call to Tendermint RPC, which in turn calls **abci\_query** in the Cosmos SDK and delegates the task to the appropriate module. To prevent potential attack vectors, such as using a wasm contract with an infinite loop to create a DoS attack on a public RPC node that exposes querying, a fixed gas limit needs to be defined for all **query\_custom** transactions called externally. This limit is not used to charge a fee but is instead used to limit abuse. However, it is challenging to define a standard value for the gas limit since a publicly exposed node would likely set a small gas limit, while an archive node performing complex queries would require a different value. To address this issue, a gas limit for all **query\_custom** calls can be defined in an app-specific configuration file. Node operators can customize this value, while a sensible default limit is set to allow public nodes to protect themselves from complex queries. Optional queries can perform large aggregations over all contract data in specially-configured nodes. It's important to note that the **abci\_query** call never reads the current "in-progress" state of the modules. Instead, it uses a read-only snapshot of the state after the last committed block. ## Internal queries While many interactions between contracts can easily be modeled by sending messages, there are some cases where we would like to synchronously query other modules without altering their state. For example, if you wanted to resolve a name to an Address, or if you wanted to check the status of some account before enabling an action. Even though you could model this as a series of messages, that would be quite complex and create hassles when implementing simple use-cases. Note that this design would also violate one of the basic principles of the Actor Model, as each contract should only have exclusive access to its own internal state. Both query\_raw and query\_custom fail in this regard. Far from just being a theoretical issue, this may lead to concurrency and reentrancy issues if not handled correctly. As there is no need to push such safety-critical reasoning into the laps of the contract developers, the security guarantees can be embedded in the framework itself. As such, we provide the **Querier** with read-only access to the state snapshot right before the execution of the current CosmWasm message. Since we take a snapshot and both the executing contract and the queried contract have read-only access to the data before the contract execution, this is still safe due to Rust's borrowing rules. The current contract only writes to a cache, which is flushed afterward on success. Keep in mind that all queries are performed as part of a transaction, which already has a strongly enforced gas limit. All storage reads and data processing performed as part of a query are deducted from the same gas meter as the rest of the transaction and thus limit processing time. <br> # Serialization Formats ## Serialization formats Serialization in CosmWasm allows you to inspect and debug messages sent on the blockchain, as well as parse results, without the need for complex libraries or downloading custom schemas and ABIs. ## JSON JSON is self-describing, human-readable, and used in APIs everywhere. It does have some downsides, such as handling numbers over 2^53 (in that case, you can use strings), having no clear distinction between strings and base64-encoded binary, and having no hard-coded schema. We auto-generate JSON Schema descriptors for the public API of contracts, which can be used to inspect the supported API and optionally used in client-side tooling for auto-validation of messages. Note that contracts define their parsing logic for messages, and the code is not enforced by the framework. While there is extended support for JSON through cosmwasm::serde and cw-template, anyone can change it as long as client support for the custom format is provided. ## Protobuf Protobuf is a well-known and widely-supported binary format that provides a stricter schema guarantee than JSON and a more compact format. Support for Protocol Buffers and gRPC was added with the Cosmos SDK v0.39.0 upgrade. ## Cap'n proto Cap'n Proto is a super-lean encoding format with zero-copy reads and no parsing needed. This has been suggested for use in CosmWasm as an optional addition. It may be considered an opt-in format for contracts desiring such efficiency or strict schema, or possibly just used for encoding internal data structures (Params). <br> # Contract Composition With the Actor model governing message dispatch and synchronous queries, we possess all the essential building blocks required to facilitate flexible composition of contracts, whether it involves interactions with other contracts or native modules. In this section, we will elucidate the seamless integration of these components and explore avenues for extending their functionality. ## Terminology Please keep in mind that in this context, "Contracts" pertain to dynamic CosmWasm code uploaded to a specific blockchain address, whereas "Native Modules" are Cosmos SDK modules, typically written in Go, that are compiled directly into the blockchain binary. While we endorse the composability of both contract types, it's crucial to scrutinize the integration with "Native Modules" more attentively, as their usage can potentially introduce portability challenges. To mitigate these concerns, we offer abstractions that revolve around "Modules." ## Messages Both the `init` and `handle` functions have the capability to return an arbitrary number of `CosmosMsg` objects, which will then be re-dispatched within the same transaction. This mechanism ensures atomic success or rollback along with the contract execution. These messages fall into three categories: * **Contract Messages**: These messages enable calls to a specified contract address with a provided message in serialized form. * **Module Interfaces**: These interfaces are standardized and can be supported by any blockchain to expose native modules through a portable interface. * **Custom Messages**: These messages encapsulate chain-specific extensions to message types, allowing calls into custom native modules. While ideally immutable within the same chain over time, they do not guarantee portability across different chains. ## Queries Contracts have the ability to perform synchronous read-only queries within the surrounding runtime. Similar to messages, these queries can be categorized into three fundamental types: * **Contract Queries**: These queries involve reaching out to a specified contract address with a provided message in serialized form. * **Module Interfaces**: These interfaces are standardized and can be implemented by any blockchain to offer access to native modules through a universally portable interface. * **Custom Queries**: These queries encapsulate chain-specific extensions for querying custom native modules. While they should ideally remain consistent within the same chain over time, they do not offer guarantees of portability across different chains. For Cross-Contract queries, the contract needs the address of the target contract and a serialized QueryMsg in the specific format of the target contract. In return, it synchronously receives a binary serialized response in the format specified by the target contract. It's the responsibility of the calling contract to comprehend the appropriate formats. To simplify this process, contract-specific type-safe wrappers can be provided, similar to how a straightforward `query_balance` method serves as a wrapper around the query implementation offered by the Trait. ## Modules To facilitate seamless integrations with native blockchains, we are offering a series of standardized module interfaces that aim to deliver consistent functionality across all CosmWasm chains. The foundational module is the Bank module, which grants access to the underlying native tokens. This encompasses BankMsg::Send for token transfers and BankQuery::Balance along with BankQuery::AllBalances for balance inquiries and token movement. The second standardized module is Staking, which introduces standardized messages for Delegation, Undelegation, Redelegation, Withdrawal, and querying Validators and Delegations. These interfaces are designed to support a wide range of Proof of Stake (PoS) systems, extending beyond the existing staking module of the Cosmos SDK. This approach fosters a cohesive design, enabling the development of contracts that can operate seamlessly on two different blockchains, even if they are extensively customized and running on distinct Cosmos SDK versions. However, it's important to note that each module interface must be incorporated into all layers of the stack, potentially causing delays in supporting custom features. Moreover, it's not feasible to offer support for every custom module across all Cosmos SDK-based blockchains. With this in mind, it is strongly recommended to utilize the module interface whenever feasible and employ custom types as a temporary measure to maintain an agile release cycle. ## Customization **Portability**: Contracts should be capable of running on two different blockchains, each with varying Golang modules and different versions of the Cosmos SDK. Ideally, this flexibility should extend to different frameworks, such as those running on Substrate. This should be achievable by avoiding Custom messages and checking the optional features being used. Currently, the supported features are Staking, which assumes a PoS system, and iterator, which assumes the ability to perform prefix scans over storage (indicating a Merkle Tree, not a Merkle Trie). **Immutability**: Contracts are immutable and encode query and message formats in their bytecode. Allowing dispatching of sdk.Msg in native formats (JSON, Amino, or Protobuf) creates a risk that contract functionality could break if the format of native messages changes. This challenge is not theoretical, as major updates of the Cosmos SDK have produced such breaking changes in the past, and these changes cannot be applied to immutable contracts. Hence, the design must provide an immutable API to a potentially mutable runtime, a crucial consideration when developing standard module interfaces. **Extensibility**: The design should support the addition of new interfaces to contracts and blockchains without necessitating updates to intermediate layers. For instance, if you're constructing a custom blockchain application that imports x/wasm from wasmd and intends to develop contracts calling into your custom superd modules, the ideal scenario is the ability to add these message types to an additional cw-superd library for contract import, along with adding the required callbacks in superd's Go code, all without altering the cosmwasm-std, cosmwasm-vm, go-cosmwasm, or wasmd repositories. Custom variants of CosmosMsg and QueryRequest facilitate such extensibility. ## Usability Using JSON encoding for CosmWasm messages streamlines the process of exporting JSON schemas for each contract, enabling the automatic generation of client-side codecs. **Checking for Support:** To assess compatibility, you can leverage feature flags exposed as wasm export functions to define the additional features required by a contract. This empowers the host chain to inspect compatibility before permitting an upload. To implement this, certain "ghost" exports, such as `requires_staking()`, are created. These exports only pass a compatibility check if the runtime also exposes the corresponding features. When initializing `x/wasm.NewKeeper()`, you have the flexibility to specify which features are supported. **Type-Safe Wrappers:** While querying or invoking other contracts, we forego the type-checks inherent in native module interfaces, necessitating that the caller possesses the requisite knowledge. To enhance usability and maintain type-checking, it proves beneficial to implement "interface" wrappers that a contract can export. These wrappers simplify the process for other contracts to interact with it seamlessly. ### Example: ``` pub struct NameService(CanonicalAddr); impl NameService { pub fn query_name(deps: &Extern, name: &str) -> CanonicalAddr { /* .. */ } pub fn register(api: &Api, name: &str) -> CosmosMsg { /* .. */ } } ``` Instead of solely storing the CanonicalAddr of the other contract in our configuration, an alternative approach would be to store the NameService. This NameService serves as a zero-cost "newtype" built upon the original address, maintaining the same serialization format. However, it brings valuable advantages, offering type-safe utilities for conducting queries against the contract and generating CosmosMsg for registration purposes. It's important to note that these type-safe wrappers are not bound to a specific contract implementation but rather to the contract's interface. Consequently, we have the flexibility to create a compact library featuring a catalog of standard and widely-used interfaces (such as the ERCxxx specifications), all represented using these "newtypes." Contract creators can import one of these wrappers, simplifying their ability to interact with the contract, regardless of its underlying implementation, as long as it adheres to the specified interface. # Comparison With Ethereum and Solidity Contracts CosmWasm employs a distinctive approach in contrast to Ethereum when it comes to deploying and executing smart contracts. The process involves three phases to establish a functioning smart contract: * **Upload Code**: In this initial step, you exclusively upload optimized wasm code. Unlike Ethereum smart contracts, this phase doesn't require consideration of state or contract addresses. * **Instantiate Contract**: During this stage, you create a code reference with an initial state and generate a contract address. * **Execute Contract**: Once your contract is live, it can accommodate various calls based on your specific contract design. **Similarities with Ethereum include:** * Both contract instantiation and execution consume gas. * Signers have the option to send tokens to the contract alongside the message during both instantiation and execution. **Notably different from Ethereum:** * Directly sending tokens to a contract (via SendMsg) does not automatically trigger any contract code in CosmWasm. Contract execution must be explicitly requested. This design choice in CosmWasm helps mitigate potential attack vectors. For instance, in Ethereum, when tokens are transferred to a contract, the contract's fallback function is automatically activated. If this fallback function is not well-implemented or contains security vulnerabilities, it can expose the contract or even the entire system to various forms of attacks, including reentrancy attacks. ## Smart Contract Instantiation In CosmWasm, the process of uploading a contract's code and instantiating a contract is treated as distinct actions, in contrast to Ethereum's approach. This separation is designed to enable a select set of well-vetted contract archetypes to exist as multiple instances, all sharing the same underlying code while allowing for individualized configuration with different parameters. A vesting contract, for instance, is a specific type of smart contract that locks up tokens and gradually releases them over a predefined period. By employing different parameters during instantiation, you have the flexibility to create multiple instances of the same vesting contract template, tailoring each instance to specific use cases. For example, if a vesting contract supports the following parameters: ``` // VestingContract.wasm { "vesting_start_time": "1616678400", // Unix timestamp for vesting start time "vesting_duration": "31536000", // Vesting duration in seconds (1 year) "total_tokens": "1000000", // Total tokens to be vested "beneficiary_address": "xion1xyz" // Address of the beneficiary } ``` By instantiating this vesting contract with distinct parameter values, you have the capability to generate multiple instances, each tailored to accommodate diverse vesting scenarios. For instance: ``` Instance A: Employee A receives 1,000,000 tokens vested over three years. Instance B: Employee B receives 500,000 tokens vested over two years. Instance C: Advisor A receives 250,000 tokens vested over one year with a six-month cliff. ``` Utilizing a single vesting contract template and adjusting the parameters during instantiation enables the creation of distinct vesting contracts tailored to individual beneficiaries and specific vesting conditions. ## Avoiding Reentrancy Attacks \ CosmWasm takes a proactive approach to prevent reentrancy attacks, which is a critical concern given that a significant number of exploits in Ethereum stem from such attacks. To illustrate how reentrancy attacks function in Ethereum smart contracts, consider the following scenario: During the execution of a function on Contract A, an implicit or explicit call is triggered, transferring control to Contract B, which can now execute its code. Subsequently, Contract B calls back into Contract A once again. With two instances of Contract A running concurrently, meticulous state management becomes imperative before executing any remote contract. Alternatively, stringent gas limits must be enforced in sub-calls. Reentrancy attacks can provoke undefined behavior within Contract A, setting the stage for vulnerabilities and exploits, reminiscent of the Ethereum DAO hack. CosmWasm takes a distinct approach to entirely mitigate reentrancy attacks by disallowing direct contract-to-contract calls. While it seeks to facilitate contract composition, it avoids inline function calls to potentially malicious code. Instead, CosmWasm permits any contract to return a list of messages to be executed within the same transaction. This means that a contract must conclude its execution before initiating a call to another contract. Should any of the subsequent messages fail, the entire transaction reverts, including any updates to the contract's state. This approach in CosmWasm ensures atomic composition while eliminating the risk of reentrancy attacks. ## Resource Limits \ Denial of Service (DoS) attacks represent another potential threat vector for smart contracts. For instance, a malicious actor could deploy a contract designed to execute an infinite loop, effectively halting the blockchain, or flood storage capacity with excessive data writes. Fortunately, WebAssembly's inherent sandboxing, with no default access to the underlying operating system, allows us to focus primarily on establishing strict resource limits for smart contracts. It is imperative for all developers to be cognizant of these limitations. * **Memory Usage**: Upon instantiating a Wasm VM, it is allocated a default of 32MB of RAM. This allocation serves to accommodate the bytecode as well as all memory usage during contract execution, encompassing stack and heap storage. In most cases, this allocation is more than sufficient for typical contracts, but it may pose limitations for exceptionally complex zero-knowledge circuits. Nonetheless, this allocation ensures that contracts have a minimal impact on the overall memory usage of the blockchain. * **CPU Usage**: The Wasmer Runtime employed by CosmWasm incorporates metering logic within the wasm code. This logic calculates operation prices, charges accordingly, and verifies limits before every jump statement (such as loops or function calls). Consequently, it establishes a deterministic gas price, irrespective of CPU speed or platform disparities. Prior to contract execution, a wasm gas limit is established, based on the remaining Cosmos SDK gas, and gas deductions occur upon contract completion. This approach imposes a
프로젝트로 돌아가기