A method for implementing a reflection mechanism in a blockchain, a compiling method and a compiler, and a Wasm virtual machine
By encapsulating metadata when the compiler generates Wasm files in the blockchain and implementing reflection functionality in the Wasm virtual machine, the problem of cumbersome smart contract calls in high-level languages is solved, enabling flexible function calls and consistent execution results, thus improving development efficiency and security.
Patent Information
- Application Number
- CN202211066052.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2022-08-31
- Publication Date
- 2026-11-27
- Estimated Expiration
- 2042-08-31
AI Technical Summary
In existing blockchain technologies, smart contracts using high-level programming languages such as Java that do not support reflection require cumbersome branching structures when calling different functions, resulting in low development efficiency and an inability to flexibly call multiple functions within the contract.
When the compiler generates Wasm files during the compilation process, it encapsulates the metadata of the Java source code, including metadata of types and functions, and creates a linear memory region in the Wasm virtual machine. It also uses the reflection library to realize dynamic parameter acquisition and function calls, supporting reflection functionality.
It enables flexible and convenient invocation of different functions in smart contracts on the blockchain, improving development efficiency and code readability, and ensuring execution consistency and security between different nodes.
Smart Images

Figure CN115495087B_ABST
Abstract
Description
Technical Field
[0001] The embodiments in this specification belong to the field of blockchain technology, and in particular relate to a method, compilation method and compiler, and Wasm virtual machine for implementing reflection mechanism in blockchain. Background Technology
[0002] Blockchain is a new application model of computer technologies such as distributed data storage, peer-to-peer transmission, consensus mechanisms, and cryptographic algorithms. The emergence of smart contracts in the Blockchain 2.0 era has elevated the application scope of blockchain to a new level. With smart contracts, blockchain can do more than just simple transfer transactions; it can also invoke code, which can be customized by the user. Summary of the Invention
[0003] The purpose of this invention is to provide a method, compilation method and compiler, and Wasm virtual machine for implementing reflection mechanisms in blockchain, including: A method for implementing reflection in a blockchain includes: During the process of the compiler compiling the source code of a contract containing reflection programming into a Wasm file: Based on the code defining the first type in the source code / bytecode, generate the meta-information of the first type and the first function in the first type, and encapsulate the generated meta-information of the first type and the first function in the first type in the Wasm file; The contract bytecode of the second function is generated based on the reflection function code in the source code to obtain the first function type and the first function content according to the dynamic parameters at runtime; Upon receiving a transaction requesting the invocation of a contract, the virtual machine loads the Wasm file of the invoking contract and: Create a linear memory region; At least a portion of the memory in the linear memory region is initialized using the metadata in the Wasm file; The contract bytecode in the Wasm file is parsed and executed. When the bytecode of the second function is executed, the first function to be called is determined and executed in the linear memory area based on the meta-information according to the dynamic parameters of the function called in the contract transaction.
[0004] One compilation method involves the compiler compiling the source code of a contract containing reflection programming into a Wasm file: Based on the code defining the first type in the source code / bytecode, generate the meta-information of the first type and the first function in the first type, and encapsulate the generated meta-information of the first type and the first function in the first type in the Wasm file; The contract bytecode of the second function is generated based on the reflection function code in the source code, which obtains the first function type and the first function content according to the dynamic parameters at runtime.
[0005] A method for a Wasm virtual machine to execute a Wasm file compiled using the aforementioned compilation method, wherein the Wasm virtual machine loads the Wasm bytecode of the invoked contract, and includes: Create a linear memory region; At least a portion of the memory in the linear memory region is initialized using the metadata in the Wasm file; The contract bytecode in the Wasm file is parsed and executed. When the bytecode of the second function is executed, the first function to be called is determined and executed in the linear memory area based on the meta-information according to the dynamic parameters of the function called in the contract transaction.
[0006] A compiler, comprising: Meta-information generation unit, used to generate meta-information of the first type and the first function in the first type based on the code defining the first type in the source code / bytecode; An encapsulation unit is used to encapsulate the metadata of the first type and the first function in the first type generated by the metadata generation institute in the Wasm file; The second function contract bytecode generation unit is used to generate contract bytecode for a second function that obtains the first function type and the first function content based on the reflection function code in the source code.
[0007] A Wasm virtual machine for executing Wasm files compiled by the aforementioned compiler, and includes: A loading unit, used to load the Wasm bytecode of the invoked contract, and includes: Create a unit, used to create a linear memory region; The first initialization unit initializes at least a portion of the memory in the linear memory region using the metadata in the Wasm file; The execution unit parses and executes the contract bytecode in the Wasm file, and when executing the bytecode of the second function, it determines and executes the first function to be called in the linear memory area based on the meta-information according to the dynamic parameters of the function called in the contract transaction.
[0008] A blockchain node that executes smart contracts includes the aforementioned Wasm virtual machine or executes the methods described above.
[0009] A blockchain node that executes smart contracts includes: processor, A memory storing a program in which the above method is performed when the processor executes the program.
[0010] In the above embodiments, reflection functionality can be implemented in the Wasm file, enabling the Wasm program to access, inspect, and modify its own state or behavior during runtime. This is particularly beneficial when there are multiple functions, allowing developers to flexibly and easily invoke different functions within the code using reflection during contract development. Attached Figure Description
[0011] To more clearly illustrate the technical solutions of the embodiments in this specification, the drawings used in the description of the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments recorded in this specification. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0012] Figure 1 This is a schematic diagram illustrating the creation and deployment of smart contracts in a blockchain network in one embodiment; Figure 2 This is a schematic diagram illustrating the creation, deployment, and invocation of smart contracts in a blockchain network in one embodiment; Figure 3 This is a schematic diagram illustrating the creation, deployment, and invocation of smart contracts in a blockchain network in one embodiment; Figure 4 This is a schematic diagram of the bytecode structure and virtual machine module in one embodiment; Figure 5 This is a flowchart of a method for implementing a reflection mechanism in one embodiment; Figure 6 This is a schematic diagram illustrating the principle of implementing the reflection mechanism in one embodiment; Figure 7 This is a schematic diagram, or relationship diagram, of tables in linear memory and tables in ordinary memory in one embodiment; Figure 8 This is a schematic diagram of the Wasm virtual machine module in one embodiment. Detailed Implementation
[0013] To enable those skilled in the art to better understand the technical solutions in this specification, the technical solutions in the embodiments of this specification will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this specification, and not all embodiments. Based on the embodiments in this specification, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this specification.
[0014] The Blockchain 1.0 era typically refers to the development phase of blockchain applications between 2009 and 2014, primarily focused on solving the problem of decentralization in currency and payment methods. In late 2013, Vitalik Buterin published the Ethereum white paper, "Ethereum: A Next-Generation Smart Contract and Decentralized Application Platform," introducing smart contracts to the blockchain and opening up applications beyond currency, thus ushering in the Blockchain 2.0 era.
[0015] A smart contract is a computer contract that executes automatically based on defined triggering rules; it can also be seen as a digital version of a traditional contract. The concept of smart contracts was first proposed in 1994 by Nick Szabo, a legal scholar and cryptographer working across disciplines. This technology was initially hindered from practical industrial applications due to a lack of programmable digital systems and related technologies, until the emergence of blockchain technology and Ethereum provided a reliable execution environment. Because blockchain technology uses a block-chain ledger, the generated data is immutable and cannot be deleted, and the entire ledger continuously adds data, ensuring the traceability of historical data; at the same time, the decentralized operating mechanism avoids the influence of centralized factors. Smart contracts based on blockchain technology not only leverage the advantages of smart contracts in terms of cost and efficiency but also prevent malicious interference with the normal execution of contracts. By writing smart contracts digitally into the blockchain, the characteristics of blockchain technology ensure that the entire process of storage, retrieval, and execution is transparent, traceable, and tamper-proof.
[0016] A smart contract is essentially a program that can be executed by a computer. Like widely used computer programs, smart contracts can be written in high-level languages. For example, Ethereum and some Ethereum-based consortium blockchains typically provide native smart contracts written in high-level languages such as Solidity, Serpent, and LLL. These high-level smart contracts can include various complex logics to implement various business functions. At the core of Ethereum as a programmable blockchain is the Ethereum Virtual Machine (EVM), which can be run by every Ethereum node. The EVM is a Turing-complete virtual machine, meaning that various complex logics can be implemented using it. Users publish and invoke smart contracts in Ethereum, which run on the EVM. In fact, the virtual machine directly runs virtual machine code (virtual machine bytecode, hereinafter referred to as "bytecode"). Smart contracts deployed on the blockchain can be in bytecode form.
[0017] Furthermore, as a decentralized distributed system, blockchain requires maintaining distributed consistency. Specifically, in a distributed system, each of the nodes in a group has a built-in state machine. Each state machine needs to start from the same initial state, execute the same instructions in the same order, and keep each state change the same to ensure a consistent final state. However, it's difficult for the devices of the nodes participating in the same blockchain network to have the same hardware configuration and software environment. Therefore, in Ethereum, a representative of blockchain 2.0, to ensure that the process and results of executing smart contracts on all nodes are the same, a virtual machine similar to the JVM—the Ethereum Virtual Machine (EVM)—is used. The EVM can shield the differences in hardware configuration and software environment among nodes, and this sandbox-like environment can also ensure that the execution of smart contracts does not affect the blockchain platform code, other programs, or operating system on the host machine. In this way, developers can develop a set of smart contract code, compile the smart contract code locally, and then upload the compiled bytecode to the blockchain. After each node executes the same bytecode through the same EVM with the same initial state, it can obtain the same final result and the same intermediate result, while shielding the differences in the underlying hardware and environment of different nodes.
[0018] For example Figure 1 As shown, after Bob sends a transaction containing information about creating a smart contract to the Ethereum network, Node 1's EVM can execute the transaction and generate the corresponding contract instance. The transaction's `data` field can store the contract's bytecode, and the `to` field can be an empty address. After the nodes reach an agreement through the consensus mechanism, the smart contract can be successfully created on the blockchain. Figure 1 The "0x6f8ae93…" in the code represents the address of a successfully created smart contract, which users can subsequently use to invoke the contract. After the contract is created, a contract account corresponding to the "0x6f8ae93…" contract address appears on the blockchain. The contract code and account storage are stored in this contract account. The behavior of the smart contract is controlled by the contract code, while the smart contract's account storage preserves the contract's state. In other words, smart contracts enable the creation of a virtual account on the blockchain that contains both contract code and account storage.
[0019] As mentioned earlier, the `data` field of a transaction containing the creation of a smart contract can store the bytecode of that smart contract. Bytecode consists of a series of bytes, each byte representing an operation. For reasons of development efficiency and readability, developers can choose to write smart contract code in a high-level language instead of directly writing bytecode. The smart contract code written in a high-level language is compiled by a compiler to generate bytecode, which can then be packaged into the initiated transaction and deployed to the blockchain through the consensus and execution processes mentioned above. Figure 2 As shown.
[0020] like Figure 2 and 3 As shown, taking Ethereum as an example, after Bob sends a transaction containing information about calling a smart contract to the Ethereum network, the EVM of node 1 can execute the transaction and generate the corresponding contract instance. Figure 3 The `from` field of the transaction is the address of the account initiating the smart contract call, the `to` field ("0x6f8ae93…") represents the address of the called smart contract, the `value` field represents the value in Ether in Ethereum, and the `data` field stores the method and parameters used to call the smart contract. After the smart contract is called, the value of `balance` may change. Subsequently, a client can view the current value of `balance` through a specific blockchain node. Smart contracts can be executed independently on each node of the blockchain network in a prescribed manner, and all execution records and data are stored on the blockchain. Therefore, when such a transaction is completed, the blockchain stores an immutable and unlossable transaction certificate.
[0021] As mentioned earlier, the transaction for creating a smart contract is sent to the blockchain. After consensus is reached, each node on the blockchain can execute the transaction. Specifically, this can be done by the EVM virtual machine of the blockchain node. At this point, a contract account corresponding to the smart contract appears on the blockchain (including, for example, the account identifier, the contract's hash value Codehash, and the contract's storage root), and has a specific address. The contract code and account storage can be stored in the contract account's storage, such as... Figure 4As shown. The behavior of a smart contract is controlled by its contract code, while the smart contract's account storage preserves the contract's state. In other words, smart contracts enable the creation of virtual accounts on the blockchain that contain contract code and account storage. For contract deployment or update transactions, the Codehash value is generated or changed. Subsequently, blockchain nodes can receive transaction requests to invoke the deployed smart contract. These requests can include the address of the invoked contract, the functions within the invoked contract, and the input parameters. Generally, after consensus is reached, each blockchain node can independently execute the specified invoked smart contract.
[0022] Figure 4 The left side shows an example of a smart contract written in Solidity. This smart contract is compiled by a compiler to generate bytecode. `solc` in the diagram is Solidity's command-line compiler. Ethereum smart contracts written in Solidity can be compiled using the `solc` command-line tool with parameters, thereby generating bytecode that can run on the EVM. After the above... Figure 1 , Figure 2 The process of deploying a contract involves successfully creating a smart contract on the blockchain. After deployment, a contract account corresponding to the smart contract is generated on the blockchain. This contract account includes elements such as an account identifier (Identity), the contract's hash value (Codehash), and the contract's storage root (StorageRoot), and has a specific address. The contract code and account storage can be stored in the contract account's storage. The Codehash is generally the hash value of the contract's bytecode. After the contract is deployed, the Codehash is the hash value of the contract's bytecode. When the contract is updated, the hash of the contract's bytecode generally changes, and the Codehash is also generally updated accordingly.
[0023] The execution of the contract can be specifically as follows: Figure 4As shown. For example, a transaction calling a contract is sent to the blockchain network, and after consensus is reached, each node can execute the transaction. The `to` field of the transaction indicates the address of the contract being called. Any node can find the storage of the contract account based on the contract address, and then read the Codehash from the storage of the contract account, thereby finding the corresponding contract bytecode based on the Codehash. The node can load the contract bytecode from storage into the virtual machine. Then, the interpreter interprets and executes it, including parsing the bytecode of the called contract (such as Push, Add, SGET, SSTORE, Pop, etc.), obtaining the opcode and function, and storing these opcodes in the memory space allocated by the virtual machine (alloc, corresponding to the memory release operation after program execution, as shown in Free in the figure), and also obtaining the jump code of the called function in the memory space. Generally, after calculating the Gas required to execute the contract and ensuring sufficient Gas, the system jumps to the corresponding address in Memory to retrieve the OPcode of the called function and begins execution. It then performs data computation, pushes / pops data from the stack, and other operations to complete the computation. During this process, some contract context information may be needed, such as the block number and information about the initiator of the call; this information can be obtained from the context (using a Get operation). Finally, the resulting state is stored in the database storage by calling the storage interface. It should be noted that during contract creation, certain functions within the contract may also be executed, such as initialization functions. In this case, code parsing, jump instructions are generated, data is stored in Memory, and data is manipulated within the stack.
[0024] In reality, high-level languages such as C, C++, Java, Go, and Python each have their own advantages. For example, C has higher execution efficiency; C++ and Java have a wide audience, a large number of developers, and mature communities and tools; Go is more modern; and Python is relatively simpler and easier to use. Currently, various blockchain platforms are expanding their smart contract types to support smart contracts developed in high-level languages such as C, C++, Java, Go, and Python. One way to achieve this expansion is by compiling the contract bytecode into the WASM (WebAssembly) format. WebAssembly is an open standard developed by the W3C community group. It is a secure, portable low-level code format designed for efficient execution and compact representation, achieving near-native performance and providing a compilation target for languages such as C, C++, Java, and Go. The WASM virtual machine was initially designed to solve the increasingly serious performance problems of web applications. Due to its superior characteristics, it has been increasingly adopted by non-web projects, such as replacing the EVM smart contract execution engine. The WebAssembly virtual machine (also known as the Wasm virtual machine or Wasm runtime environment, which is a virtual machine runtime environment that executes WASM bytecode), implemented according to the W3C community open standard, is implemented by loading Wasm bytecode at runtime and interpreting it for execution. The execution process of Wasm bytecode in the Wasm virtual machine is similar to the EVM process described above, such as... Figure 4 As shown in the image.
[0025] For example, for smart contracts written in C++, the developer can generate corresponding source files, typically with a .cpp extension, after writing the smart contract. The .cpp files of the contract code can be compiled by a compiler to generate Wasm format bytecode. The Wasm format bytecode can then be encapsulated in a .wasc file. Similarly, for smart contracts written in Java, the developer can generate corresponding source files, typically with a .java extension, after writing the smart contract. The .java files of the contract code can be compiled by a compiler to generate Wasm format bytecode. The Wasm format bytecode can then be encapsulated in a .wasc file. .wasc is a file that combines bytecode and the ABI (Application Binary Interface).
[0026] Programs developed in different high-level languages may behave differently due to the varying characteristics of these languages. For example, programs developed in Java can implement reflection functionality at runtime using the corresponding JVM virtual machine because Java has a reflection mechanism. Reflection, also known as reflection programming, refers to the ability of a computer program to access, inspect, and modify its own state or behavior at runtime. Reflection programming is a common feature in the Java programming language, typically supporting dynamic execution, while the WASM bytecode standard does not directly support reflection. Besides Java, other high-level languages with reflection programming capabilities include C#, Python, and Go. This application primarily uses Java as an example in some sections, but it also applies to C#, Python, Go, and other languages.
[0027] In blockchain, smart contracts developed by developers can provide different functions to achieve different functionalities. Subsequent contract callers can dynamically invoke one or more functions within the contract to achieve specific functionalities. For high-level programming languages that do not support reflection, developers typically need to explicitly write the conversion between method names and method calls in the code when developing the contract, which is cumbersome and verbose. For high-level programming languages that support reflection, developers can flexibly and easily implement the conversion between method names and method calls in the code when developing the contract.
[0028] For example, in high-level languages like C++ that do not support reflection programming, dynamic execution can generally be achieved through branching structures, where different methods are executed dynamically as needed. The following C++ program simulates the dynamic execution of different methods: Code Segment 1 The code snippet 1 above in the C++ contract provides functions such as `sum` and `multiply` for contract callers to initiate calls and pass parameters. Because the contract cannot know in advance which specific function will be called by an initiating transaction, an `if` branch is typically used to match the initiated contract call. Once matched, the corresponding parameters are passed to execute the function, and the result is returned. This method simulates dynamic execution, and for contracts with many functions, this part of the code becomes quite cumbersome and verbose.
[0029] Similar functionality can be achieved using reflection, for example, in Java. Code snippet 2 In the Java code above, lines 1-8 define a class named `Person`. This class includes at least two member variables and at least two member functions. The two member variables are `name` (string) and `age` (integer), and the first function is `getSum()`, and the second function is `getMultiply()`. Both `getSum()` and `getMultiply()` take two integer variables as input; the former returns the sum of the two input variables, and the latter returns the product. Besides the `Person` class, the ellipsis in line 9 indicates the definition of other classes, which can also include member variables / member functions. Lines 10-14 define a function named `getProperty`, which retrieves a property. Its input parameters include an object `p` of type `Object`, a string variable `prop`, and integer variables `arg1` and `arg2`. The specific implementation of the `getProperty()` function can first dynamically obtain the function name via line 11. For example, when a user initiates a call to a contract, it could specifically call functions like `getSum()` or `getMultiply()` within the contract. For example, if the interface functions provided to users are Sum() and Multiply(), it is impossible to predict which function in which class object will be called by the user-initiated transaction before the contract is executed. Thus, the reflection mechanism code in lines 12-13 above allows for a flexible and convenient conversion between method names and method calls. Specifically, as in the example above, line 10 defines an object `p` created by the superclass `Object` as its input parameter (classes like `Person` inherit from `Object`, so the ancestor class of objects created by `Person` is `Object`, which is also called the ancestor class); line 11 extracts the function name called by the user and prepends "get" to obtain the complete function name; line 12 contains the reflection function, which uses `p.getClass().getMethod(methodName, int.class, int.class)` to retrieve functions with the same name and the same input and output parameters (or return type) within the class to which object `p` belongs (including other subclasses inheriting from `Object`, such as `Person`); the code in line 13 uses the retrieved function to perform the calculation and returns the result. The specific implementation of the reflection code in lines 12 and 13 in the compiler and virtual machine is detailed below. This method is particularly useful when there are multiple functions, as it avoids the need for a multi-condition branching structure used in the C++ code above to simulate dynamic execution and match each function name.
[0030] For smart contracts already written in Java, reflection mechanisms may already be included. To enable the Wasm virtual machine to implement reflection when executing compiled Wasm files, the compiler can perform actions such as... during the compilation of Java source code into Wasm files. Figure 5 and Figure 6 The process shown: S110: Generate metadata of the first type and the first function in the first type according to the code defining the first type in the source code, and encapsulate the generated metadata of the first type and the first function in the first type in the Wasm file.
[0031] For example, in Java source code, types (often simply called classes) can be defined, such as `ClassPerson { ...}` in the Java code above. The `{ ...}` can contain member variables and member functions. Multiple classes can be defined in a single Java file, and each class can define multiple member functions. Each member function typically includes a return type, function name, and input parameters. These types can be collectively referred to as primary types, and these member functions can be collectively referred to as primary functions. Here, "primary" can be understood as "the first type" or "the first category." Based on the defined classes, objects can be created from those classes. Using classes and objects is the primary means of object-oriented programming. An object is an abstraction of an objective thing; a class is an abstraction of an object. Their relationship is that an object is an instance of a class, and a class is a template for objects.
[0032] The metadata for the first type and the first function can be encapsulated in a wasm file. The metadata for the first type and the first function can at least include the structure of the first type object and the structure of the first function. Because everything in Java is an object, and a type is also a special type of object, a special type object also has its own type and fields. The type to which it belongs can then be found based on this first type object. In addition, it can also include the first type structure and / or the first type's field structure. Whether the first type structure and the first type's field structure are included depends on the compiler's compilation scheme and may also depend on whether the first function uses fields of the first type, such as if the implementation of the first function requires the use of one or more fields from the first type. In a specific example, the metadata for the first type and the first function can include the structure of the first type object, the first type structure, the first type's field structure, and the structure of the first function, as shown below: - First type object structure: --A linear memory address for an object type that is 4 bytes; -- The linear memory addresses of the array of fields of the object; - First type structure: --4 bytes, the linear memory address of the type name string; --4 bytes, the linear memory address of an array of fields of type; --4 bytes, the linear memory address of an array of methods and functions of type 4; - First type of field structure: --4 bytes, the number of fields in the type; --4 bytes, the linear memory address of the field name string; --4 bytes, the linear memory address of the field's return type; - Function structure of type 1: --4 bytes, the number of methods / functions of the type; --4 bytes, the index of the function in the function table; --4 bytes, the linear memory address of the function name string; --4 bytes, the linear memory address of the function return type; --4 bytes, the number of function parameters; --The linear memory address of the type array of each parameter; ...... In the above metadata, the preceding "-" indicates the first level, and "--" indicates the second level. The second level belongs to the nearest first level above it.
[0033] The metadata of the first type and the first function in the first type can be encapsulated in a Wasm file.
[0034] Specifically, this metadata, after being loaded by the Wasm virtual machine, can be loaded into the linear memory managed by the Wasm virtual machine. The linear memory managed by the Wasm virtual machine has logical addresses, not logical addresses in system memory. Here, during the process of encapsulating this metadata in the Wasm file, the logical address in the linear memory where this metadata resides can be determined. In addition, the virtual machine can also manage non-linear memory, i.e., ordinary memory, as will be discussed later.
[0035] The Wasm virtual machine achieves at least part of the sandboxing and deterministic goals through linear memory. First, the memory addresses in the Wasm file are all within the range of 0 to the linear memory capacity, never exceeding this linear memory area. This ensures that Wasm bytecode, when executed by the virtual machine, will not read memory outside the linear memory managed by Wasm; that is, it cannot read any external information unless called through the host API. Thus, all Wasm instructions read and write addresses within linear memory, preventing out-of-bounds access and achieving the sandboxing goal. Secondly, in the context of this application, the various metadata of classes (i.e. types) in the Wasm file are determined at compile time. In particular, the logical addresses of classes and their member variables and member functions in linear memory are also determined in the context of this application. Therefore, the process of loading the same contract Wasm file and executing the contract bytecode in it through the Wasm virtual machine on different nodes can ensure that the various metadata in the class are consistent. Specifically, the logical addresses of classes and their member variables and member functions in linear memory are also consistent (even the various information generated based on the logical addresses are consistent and will not differ due to the randomness of ordinary memory). That is, the same contract bytecode will not have inconsistent execution results in the Wasm virtual machine on different nodes due to minor differences, thus achieving the goal of determinism.
[0036] Conversely, executing C++ code directly without using the Wasm virtual machine will result in inconsistent performance due to memory randomness. This inconsistency extends beyond different nodes; even multiple executions of the same program on the same node will lead to inconsistent results. For example, creating an object using the `new` statement based on a class definition will likely result in a different memory address each time, as this address is typically randomly allocated by the operating system based on available memory. If the program logic involves calculating subsequent data based on this address, inconsistent execution results will occur. Similarly, hash tables in some implementations calculate hashes based on object addresses, leading to inconsistent hash table storage order. Subsequent hash table traversal operations will also result in inconsistent order.
[0037] Based on the above Java source code, the metadata of the first type and the first function can be as follows: Table 1. Type Structure It should be noted that the 4 bytes mentioned above are merely examples and not limitations.
[0038] In addition, as shown in the table above, linear memory can also store the specific contents of type structures, as shown in Table 2 below: Table 2. Contents of Type Structure As can be seen, the addresses of some fields in the columns on the left side of Table 1 point to some fields in Table 2. This mapping relationship will be explained in detail later. It should be noted that the memory locations of the fields in Table 1 are generally contiguous, which facilitates the search for related structures and fields of the same type in memory; in addition, the fields within at least one of the four blocks in Table 1 are contiguous, so that each field can be accessed by traversing from the starting address using pointers in the subsequent code segment 4. However, the fields in Table 1 store addresses pointing to the fields in Table 2, meaning that the fields in Table 2 can be found in memory through the addresses in Table 1. Therefore, the memory locations of the fields in Table 2 do not need to be contiguous.
[0039] Specifically, during the compilation process, the wasm function module is processed as follows: (module (table 1 funcref) / / table is an array containing all virtual methods (func $Person_getSum(result i32)(param i32 i32)...) (func $Person_getMultiply(result i32)(param i32 i32 )...) (elem(i32.const O) $Person_getSum $Person_getMultiply) / / The getSum function is placed in a table with index 1; the getMultiply function is also placed in a table with index 2. (data 0 “01010101010101”) / / Represents the initial linear memory data segment, containing binary data of the above type structure. ) Code snippet 3 Code segment 3 above means retrieving the function name string, return type, and input parameter types from the class and filling them into the corresponding fields in Table 2. It also fills Table 1 with the linear memory addresses and number of parameters for each field of the function in Table 2, creates an index for the function class, and establishes an entry for index 3 in Table 3. This index is then filled into the corresponding field in Table 1. For example, the `getSum` function is placed in `table` with index 1, and the `getMultiply` function is also placed in `table` with index 2.
[0040] S120: Generate second function bytecode based on the reflection function code in the source code, which obtains the first function type and the first function content according to the dynamic parameters at runtime.
[0041] During the compilation process, support for reflection functionality can be added to the source code. The compiler organizes the Java source code into a suitable format, including lexical / syntactic analysis based on the abstract syntax tree, symbol table filling, annotation processing, semantic analysis, and code generation, ultimately encoding the source code into Wasm bytecode. During this process, when compiling reflection functionality code, the compiler can generate corresponding second function bytecode that retrieves the first function type and content based on runtime dynamic parameters. For example, in the Java code in the example above, lines 12-13 contain reflection functionality code, and the corresponding bytecode is the second function bytecode.
[0042] Specifically, to support reflection functionality, a reflection library is typically provided, which includes classes that support reflection. During source code writing, developers can import this reflection library at the beginning of the class file, for example, using an `import` statement, following syntax rules. When the compiler compiles the source code, it can replace the reflection code in the project files with the relevant statements from the reflection library, thereby performing the lexical / syntactic analysis, symbol filling, annotation processing, semantic analysis, and code generation processes described above, ultimately generating the contract bytecode in the Wasm file.
[0043] For example, the imported reflection library contains concrete implementations of Class.getMethod() and Method.invoke() in lines 12 and 13 above. Thus, during compilation, the reflection functionality code in the source code—namely, the Class.getMethod() and Method.invoke() methods in lines 12 and 13—can be replaced with the corresponding concrete implementations from the reflection library.
[0044] The provided reflection library may include specific implementations of Class.getMethod() and Method.invoke().
[0045] The implementation of Class.getMethod() is as follows: class Class { The main principle is that type information is stored in the wasm linear memory, followed immediately by an array of method metadata for the type. public Method[] getDeclaredMethods() { / / Get the indices of each method function from the class structure's methodIndex array. / / castType is a type conversion function. During Wasm runtime, each object is represented as an int32 address. RuntimeClass runtimeClass = castType(this); / / Based on the size of the stored class structure, quickly find the array of methods that follows the class structure. int runtimeClassStructureSize = runtimeClass.classStructureSize; / / Get the starting address of the array of method addresses of the type Address runtimeClassMethodIndexArrayAddress = Address.ofObject( runtimeClass).add(runtimeClassStructureSize); / / Size of the virtual table for this type (its own size + number of inherited virtual methods) int vtableSize = runtimeClass.vtableSize; Method[] methods = new Method[vtableSize]; / / Starting memory address of the methods metadata array in Table 1 Address methodsPointer = runtimeClassMethodIndexArrayAddress; for (int i=0; i <vtableSize; i++) { / / methodIndex is the index of the function corresponding to this Java method in the wasm table. int methodIndex = methodsPointer.getInt(); methodsPointer = methodsPointer.add(4); / / Move the pointer 4 bytes in Table 1 / / Read method name, return type, params, etc., omitted here. / / get method info and put method in TMethod[] Method method = new Method(this, methodIndex); methods[i] = method; } return methods; } } Code snippet 4 Code snippet 4 above is pseudocode for the specific implementation of `Class.getMethod` in the reflection library. As mentioned earlier, the reflection library containing this code can be imported. This allows the imported reflection function code to replace the calls in the user-written Java code during compilation. In code snippet 4, the function name concatenated in line 11 is used to iterate through the array of method objects of the type obtained in code snippet 4 until a first function with the same name string is matched, thus obtaining the index of that first function in Table 1.
[0046] The implementation of Method.invoke() is as follows: Class Method{ int funcIndex; / / The index of the wrapper Java method's wasm function, for example, the index of the getSum function is 1. Object invoke(Object obj, Object... args){ switch(args.length){ case 0: return call indirect(funcIndex); case 1: return call indirect(funcIndex, args[0]); case 2: return call indirect(funcIndex, args[0], args[1]); ... case n: return call_indirect(funcIndex, args[0], ... args[n-1]); ... } } } Code snippet 5 Code snippet 5 above is pseudocode for the specific implementation of `Method.invoke` in the reflection library. In code snippet 2 above, the index of the first function matching the name string in Table 1 is obtained through the `Class.getMethod()` function on line 12. Specifically, this can be obtained through `p.getClass().getMethod()`, the implementation of which is as described in code snippet 4 above. Then, line 13 of code snippet 2 can be executed, that is, a call is initiated to the corresponding first function. Specifically, in code snippet 5, if the number of parameters in the corresponding case matches the number in Table 1, an indirect call is performed based on the number of input parameters. For example, if the index of `getSum` in Table 1 is 1, line 12 of code snippet 2 can match the index 1 of the `getSum` string in Table 1. Then, the two parameters input to the `getSum` function can be verified again through the switch statement in code snippet 5, confirming that `funcIndex` in case 2 is 1 and there are two parameters. In this way, an indirect call to the function with funcIndex of 1 can be initiated. That is, the starting address of the getSum() function in the subsequent table 4 can be found by index 1 in the subsequent table 3, and then the virtual machine can parse the code at the corresponding starting address in table 4 and execute it.
[0047] The aforementioned WASC file can be deployed to the blockchain using the contract deployment process described above. The deployed contract can then be invoked. As mentioned earlier, a client can initiate a transaction to invoke the contract, for example... Figure 6 Client 2. The client can pre-determine the interfaces supported by the contract by querying its ABI. For example, by querying the contract's ABI, the client can find that the interface function includes `sum(a)`. Thus, the client can initiate a transaction to call the contract. This transaction can include the address of the contract being called, the function being called, and the input parameters (i.e., input parameters). The called function and input parameters are located in the `data` field, for example, `sum()`, `1`, respectively.
[0048] After the transaction in the call contract has reached a consensus, each blockchain node can execute the transaction. In some blockchain systems, some or all nodes may execute the transaction first, and then reach a consensus; there is no restriction on this.
[0049] The blockchain node executes the transaction; specifically, this includes the virtual machine within the node loading and executing the bytecode of the invoked contract. The virtual machine can first load the wasm file of the contract specified in the transaction to be executed, which includes the contract's bytecode, and then proceed roughly as described above. Figure 4The process will be explained and executed, and the special features will be further described below.
[0050] First, a contract can include an entry function. This entry function can be used to match functions like `sum()` and `1` with their input parameters to functions within the contract. For example, consider the following code: @ContractInterface / / Indicates that the following is the exposed contract interface. public int sum(int a) { int b = 1024; int sum = (Integer) getProperty(new Person(), “Sum”, a, b); return sum; } } Code snippet 6 Thus, `sum(), a` is converted into an implementation of `getProperty()`. The input parameters of `sum()` can differ from those of `getProperty()`. For example, `sum()` takes one parameter `a`, while `getProperty()` takes two parameters `a` and `b`, in addition to the called object and the name of the called method. According to the code above, one of the two parameters `a` in `getProperty()` is the same as the parameter `a` in the `sum()` function. The other parameter `b` in `getProperty()` can be set to a value defined in the contract. This value can be a constant or a global variable, the latter being read from the contract state, for example. Combining this with the implementation defined in lines 10-14 of code segment 2, the conversion of `sum()` into the `getProperty()` function can be achieved.
[0051] according to Figure 5 and Figure 6 As shown, the virtual machine loads the Wasm file of the calling contract and executes the following process: S210: Create a linear memory region.
[0052] Physical memory is typically managed by the operating system, which is responsible for establishing the mapping between logical addresses and physical addresses. The Wasm virtual machine can maintain a linear memory region, which is a portion of the memory managed by the operating system and is managed and controlled by Wasm. Specifically, Wasm can add another layer of abstraction on top of the operating system-managed memory, resulting in a linear memory region with addresses starting from 0, and can control access to this linear memory based on offsets. As mentioned earlier, the Wasm virtual machine can also manage a portion of non-linear memory, referred to here as ordinary memory.
[0053] After the Wasm virtual machine loads the Wasm file, it can create a linear memory region before executing the contract bytecode.
[0054] S220: Initialize at least a portion of the memory in the linear memory region using the metadata in the Wasm file.
[0055] As mentioned earlier, the Wasm file contains metadata about types and functions, as well as contract bytecode. After loading the Wasm file, the Wasm virtual machine can create a linear memory region. The virtual machine can then use the metadata about the first type and first function contained in the Wasm file to initialize at least a portion of the linear memory. As described above, the address of linear memory can start from 0, which can be called the base address of linear memory in the operating system; other addresses in linear memory are equivalent to offsets relative to this base address. Thus, address 'a' in linear memory corresponds to the base address of linear memory in the operating system plus the offset 'a' in linear memory. By abstracting the operating system memory in this way, the Wasm virtual machine can better manage and use memory.
[0056] In this way, the linear memory is non-empty before the contract bytecode is executed; before the contract bytecode instructions are executed, the constants, class and function metadata in the code are pre-included in the linear memory, and the address in the linear memory is fixed, which facilitates the deterministic calling of the subsequent Wasm bytecode during execution.
[0057] Furthermore, as mentioned earlier, after the Wasm virtual machine loads the Wasm file, it can create a general memory area. The virtual machine can then initialize at least a portion of the general memory using the first and second function bytecode contained in the Wasm file. Functions called by objects instantiated from a class during execution reside in the storage area corresponding to the class. This storage area is generally located in the general memory created by the virtual machine. In other words, functions within a class reside in the general memory area. Since objects created from a class are instantiated from that class, when executing functions within the class, the corresponding functions, including the first and second functions, need to be loaded and executed from general memory.
[0058] After the virtual machine initializes at least a portion of the ordinary memory using the first function, it can generate two tables: Table 3, the function table, and Table 4, the function code table.
[0059] The function table can be shown in the following table: Table 3. Function Table in Ordinary Memory The function code can be shown in the table below: Table 4. Functions in ordinary memory For example, the first function includes function 1, function 2, function 3, and so on. As shown above, in Table 4, the code data block of function 1 is stored in ordinary memory and has a starting address in ordinary memory managed by the virtual machine. Similarly, the code data block of function 2 has a starting address in ordinary memory, and the code data block of function 3 has a starting address in ordinary memory. The function table in Table 3 can store the starting addresses of each function's code in ordinary memory in a concise and orderly format, for example, each row in Table 3 contains a 32-bit address.
[0060] As can be seen, the first function in the first type mentioned above can include multiple functions. To facilitate unified management of functions in the first type in memory, the starting address of each function in ordinary memory in Table 4 can be filled into the corresponding position in Table 3, so that different function codes can be uniformly mapped by this function table.
[0061] During the process of generating Table 3, the starting address of Table 3 in ordinary memory can be obtained. Therefore, based on the starting address and index of Table 3, the starting address of the corresponding function in Table 4 can be obtained.
[0062] Combining Tables 1, 2, 3, and 4 above, a complete mapping table can be constructed. This mapping table can be viewed as follows: Figure 7As shown. Tables 1 and 2 can be stored in linear memory, their addresses determined by the compiler at compile time and remaining fixed; Tables 3 and 4 are stored in ordinary memory. Each entry in the function table of Table 3 points to the starting address of the corresponding function code in Table 4. From the virtual machine's perspective, it can be viewed as follows... Figure 8 As shown.
[0063] S230: Parse and execute the contract bytecode in the Wasm file, and when the bytecode of the second function is executed, determine the first function to be called in the linear memory area based on the meta-information according to the dynamic parameters of the function called in the contract transaction and execute it.
[0064] During the loading of the contract bytecode in the Wasm file into the virtual machine, the functions within the class are also loaded into the virtual machine's ordinary memory, as described above regarding the initialization process of ordinary functions. At runtime, the Wasm bytecode involves numerical calculations, memory read / write operations, and function calls. The memory space operated on by the Wasm bytecode is linear memory created before runtime and cannot directly manipulate ordinary memory. Ordinary memory can be manipulated by the virtual machine, thus ensuring that the contract bytecode does not directly modify the function bytecode in ordinary memory.
[0065] The virtual machine parses and executes the contract bytecode in the Wasm file, following the logic within the bytecode. When executing the reflection code in the second function bytecode, the actual function to be called can be dynamically determined based on the dynamic parameters of the function called in the contract transaction. Specifically, when executing the bytecode of the second function: When the execution reaches line 11 of the code segment 2 above, the function name concatenation is completed; When the execution reaches line 12 (which actually also includes the content of the replaced code segment 4), the function name concatenated from line 11 is used to traverse the virtual table until the first function with the same name string is matched, thereby obtaining the index of the first function in table 1; When execution reaches line 13 of code segment 2 (which also includes the content of the replaced code segment 5), the corresponding first function is called. Specifically, in code segment 5, the number of parameters in the corresponding case is verified again based on the number of input parameters. If the number matches the corresponding number in Table 1, an indirect call is made. For example, if the index of getSum in Table 1 is 1, line 12 of code segment 2 (and the content of the replaced code segment 4) can match the getSum string to index 1 in Table 1. Then, the two parameters input to the getSum function can be verified again by the switch statement in code segment 5, confirming that funcIndex in case 2 is 1 and has two parameters. Thus, an indirect call to the function with funcIndex 1 can be initiated. That is, the starting address of the getSum() function in subsequent Table 4 is found through index 1 in subsequent Table 3, and the code at the corresponding starting address in Table 4 is parsed and executed.
[0066] Similarly, for example, if the index of `getMultiply` in Table 1 is 2, then line 12 of code segment 2 (and the content of the replaced code segment 4) can be used to match the string `getMultiply` to find the index 2 in Table 1. Furthermore, the two parameters input to the `getMultiply` function can be verified again using the switch statement in code segment 5, confirming that `funcIndex` in case 2 is 2 and that there are also two parameters. Thus, an indirect call to the function with `funcIndex` 2 can be initiated. Specifically, the starting address of the `getMultiply()` function in subsequent Table 4 can be found using index 2 in subsequent Table 3, and the code at the corresponding starting address in Table 4 can be parsed and executed.
[0067] The above example allows for the determination and execution of the first function to be called based on the function name string of the function called in the contract transaction within the linear memory area using the metadata. Besides the concatenated string mentioned above, the string can also be a user-inputted string, or a string constructed from integers or binary data.
[0068] Through the above embodiments, reflection functionality can be implemented in Wasm files, enabling the access, inspection, and modification of the Wasm program's own state or behavior during runtime. This is particularly beneficial when multiple functions are involved, allowing developers to flexibly and easily invoke different functions within the code using reflection. For example, developers can create Java source code incorporating reflection programming capabilities. Reflection programming, for instance, involves obtaining the type of an object, including its fields and methods. Specifically, blockchain platform vendors can provide auxiliary functions, such as those located in a reflection library. These auxiliary functions may include APIs for obtaining type and function metadata. This library can be provided to developers, who can then include these library functions in their source code when developing smart contracts using high-level languages, and call these APIs within the library to obtain type and function metadata within the source code. Alternatively, existing function libraries can be used, such as Java's built-in reflection programming library, allowing developers to incorporate the reflection programming functionality provided by that library when developing Java source code.
[0069] As mentioned above, smart contracts written in Java can generate corresponding source files after the contract developer completes the contract, typically with a .java extension. The .java file containing the contract code can be compiled by a compiler to generate Wasm format bytecode. This Wasm format bytecode can then be encapsulated in a .wasc file. Furthermore, Java bytecode may be developed in other blockchain systems that support reflection functionality, such as files with a .class extension. This Java bytecode contains code with reflection capabilities. Such Java bytecode is an equivalent program to Java source code; therefore, the compiler described in this embodiment can be used to recompile this Java bytecode containing reflection capabilities to generate Wasm bytecode. The generated Wasm bytecode also contains reflection capabilities, allowing reflection to be implemented when the virtual machine executes the Wasm bytecode.
[0070] Furthermore, as mentioned earlier, high-level languages with reflection programming capabilities include not only Java, but also C#, Python, and Go. Contract code developed in some programming languages that do not natively support reflection mechanisms can also implement reflection functionality using the reflection library, compiler, and virtual machine provided in this application, such as C++.
[0071] Based on the above solution, this application embodiment also provides a compilation method, in which the compiler compiles the contract source code containing reflection programming into a Wasm file: Based on the code defining the first type in the source code / bytecode, generate the meta-information of the first type and the first function in the first type, and encapsulate the generated meta-information of the first type and the first function in the first type in the Wasm file; The contract bytecode of the second function is generated based on the reflection function code in the source code, which obtains the first function type and the first function content according to the dynamic parameters at runtime.
[0072] Based on the above scheme, this application embodiment also provides a method for the Wasm virtual machine to execute a Wasm file compiled by the aforementioned compilation method, wherein the Wasm virtual machine loads the Wasm bytecode of the called contract, and includes: Create a linear memory region; At least a portion of the memory in the linear memory region is initialized using the metadata in the Wasm file; The contract bytecode in the Wasm file is parsed and executed. When the bytecode of the second function is executed, the first function to be called is determined and executed in the linear memory area based on the meta-information according to the dynamic parameters of the function called in the contract transaction.
[0073] The method further includes creating a general memory region and initializing at least a portion of the general memory using first and second function bytecode contained in a Wasm file.
[0074] The method, wherein the initialization of at least a portion of the ordinary memory using first function bytecode and second function bytecode contained in the Wasm file, includes: A function table and function code are generated in the ordinary memory, wherein the function table stores the starting address of the memory where the function code is located.
[0075] Based on the above solution, this application also provides a compiler, including: Meta-information generation unit, used to generate meta-information of the first type and the first function in the first type based on the code defining the first type in the source code / bytecode; An encapsulation unit is used to encapsulate the metadata of the first type and the first function in the first type generated by the metadata generation institute in the Wasm file; The second function contract bytecode generation unit is used to generate contract bytecode for a second function that obtains the first function type and the first function content based on the reflection function code in the source code.
[0076] Based on the above solution, this application also provides a Wasm virtual machine for executing Wasm files compiled by the aforementioned compiler, and includes: A loading unit, used to load the Wasm bytecode of the invoked contract, and includes: Create a unit, used to create a linear memory region; The first initialization unit initializes at least a portion of the memory in the linear memory region using the metadata in the Wasm file; The execution unit parses and executes the contract bytecode in the Wasm file, and when executing the bytecode of the second function, it determines and executes the first function to be called in the linear memory area based on the meta-information according to the dynamic parameters of the function called in the contract transaction.
[0077] Based on the above solution, this application embodiment also provides a blockchain node for executing smart contracts, including the Wasm virtual machine described in the foregoing embodiments or the method described above.
[0078] Based on the above solution, this application embodiment also provides a blockchain node for executing smart contracts, including: processor, A memory that stores a program in which the above-described method is performed when the processor executes the program.
[0079] In the 1990s, improvements to a technology could be clearly distinguished as either hardware improvements (e.g., improvements to the circuit structure of diodes, transistors, switches, etc.) or software improvements (improvements to the methodology). However, with technological advancements, many methodological improvements today can be considered direct improvements to the hardware circuit structure. Designers almost always obtain the corresponding hardware circuit structure by programming the improved methodology into the hardware circuit. Therefore, it cannot be said that a methodological improvement cannot be implemented using hardware physical modules. For example, a Programmable Logic Device (PLD) (such as a Field Programmable Gate Array (FPGA)) is such an integrated circuit whose logic function is determined by the user programming the device. Designers can program and "integrate" a digital system onto a PLD themselves, without needing chip manufacturers to design and manufacture dedicated integrated circuit chips. Furthermore, nowadays, instead of manually manufacturing integrated circuit chips, this programming is mostly implemented using "logic compiler" software. Similar to the software compiler used in program development, the original code before compilation must also be written in a specific programming language, called a Hardware Description Language (HDL). There are many HDLs, such as ABEL (Advanced Boolean Expression Language), AHDL (Altera Hardware Description Language), Confluence, CUPL (Cornell University Programming Language), HDCal, JHDL (Java Hardware Description Language), Lava, Lola, MyHDL, PALASM, and RHDL (Ruby Hardware Description Language). Currently, the most commonly used are VHDL (Very-High-Speed Integrated Circuit Hardware Description Language) and Verilog. Those skilled in the art should also understand that by simply performing some logic programming on the method flow using one of these hardware description languages and programming it into an integrated circuit, the hardware circuit implementing the logical method flow can be easily obtained.
[0080] The controller can be implemented in any suitable manner. For example, it can take the form of a microprocessor or processor and a computer-readable medium storing computer-readable program code (e.g., software or firmware) executable by the (micro)processor, logic gates, switches, application-specific integrated circuits (ASICs), programmable logic controllers, and embedded microcontrollers. Examples of controllers include, but are not limited to, the following microcontrollers: ARC 625D, Atmel AT91SAM, Microchip PIC18F26K20, and Silicon Labs C8051F320. A memory controller can also be implemented as part of the control logic of the memory. Those skilled in the art will also recognize that, in addition to implementing the controller in purely computer-readable program code form, the same functionality can be achieved by logically programming the method steps to make the controller take the form of logic gates, switches, application-specific integrated circuits, programmable logic controllers, and embedded microcontrollers. Therefore, such a controller can be considered a hardware component, and the means included therein for implementing various functions can also be considered as structures within the hardware component. Alternatively, the means for implementing various functions can be considered as both software modules implementing the method and structures within the hardware component.
[0081] The systems, devices, modules, or units described in the above embodiments can be implemented by computer chips or physical entities, or by products with certain functions. A typical implementation device is a server system. Of course, this application does not exclude the possibility that, with the future development of computer technology, the computer implementing the functions of the above embodiments can be, for example, a personal computer, a laptop computer, an in-vehicle human-machine interaction device, a cellular phone, a camera phone, a smartphone, a personal digital assistant, a media player, a navigation device, an email device, a game console, a tablet computer, a wearable device, or any combination of these devices.
[0082] While one or more embodiments of this specification provide the operational steps of the methods described in the embodiments or flowcharts, more or fewer operational steps may be included based on conventional or non-inventive means. The order of steps listed in the embodiments is merely one possible order of execution among many steps and does not represent the only possible order. In actual device or end product execution, the methods shown in the embodiments or drawings may be executed sequentially or in parallel (e.g., in a parallel processor or multi-threaded processing environment, or even a distributed data processing environment). The terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, product, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, product, or apparatus. Without further limitations, the presence of other identical or equivalent elements in the process, method, product, or apparatus that includes said elements is not excluded. For example, the use of terms such as "first," "second," etc., is to denote names and does not indicate any particular order.
[0083] For ease of description, the above devices are described in terms of function, divided into various modules. Of course, when implementing one or more of these specifications, the functions of each module can be implemented in one or more software and / or hardware components, or a module that performs the same function can be implemented by a combination of multiple sub-modules or sub-units. The device embodiments described above are merely illustrative. For example, the division of units is only a logical functional division; in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces, indirect coupling or communication connection between devices or units, and may be electrical, mechanical, or other forms.
[0084] This invention is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of the invention. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart illustrations and / or block diagrams. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0085] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0086] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0087] In a typical configuration, a computing device includes one or more processors (CPU), input / output interfaces, network interfaces, and memory.
[0088] Memory may include non-persistent storage in computer-readable media, such as random access memory (RAM) and / or non-volatile memory, such as read-only memory (ROM) or flash RAM. Memory is an example of computer-readable media.
[0089] Computer-readable media, including both permanent and non-permanent, removable and non-removable media, can store information using any method or technology. Information can be computer-readable instructions, data structures, program modules, or other data. Examples of computer storage media include, but are not limited to, phase-change memory (PRAM), static random access memory (SRAM), dynamic random access memory (DRAM), other types of random access memory (RAM), read-only memory (ROM), electrically erasable programmable read-only memory (EEPROM), flash memory or other memory technologies, CD-ROM, digital versatile optical disc (DVD) or other optical storage, magnetic tape, magnetic magnetic disk storage, graphene storage or other magnetic storage devices, or any other non-transferable medium that can be used to store information accessible by a computing device. As defined herein, computer-readable media does not include transient computer-readable media, such as modulated data signals and carrier waves.
[0090] Those skilled in the art will understand that one or more embodiments of this specification can be provided as a method, system, or computer program product. Therefore, one or more embodiments of this specification may take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, one or more embodiments of this specification may take the form of a computer program product implemented on one or more computer-usable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0091] One or more embodiments of this specification can be described in the general context of computer-executable instructions, such as program modules, that are executed by a computer. Generally, program modules include routines, programs, objects, components, data structures, etc., that perform a particular task or implement a particular abstract data type. One or more embodiments of this specification can also be practiced in distributed computing environments where tasks are performed by remote processing devices connected via a communication network. In a distributed computing environment, program modules can reside in local and remote computer storage media, including storage devices.
[0092] The various embodiments in this specification are described in a progressive manner. Similar or identical parts between embodiments can be referred to mutually. Each embodiment focuses on describing the differences from other embodiments. In particular, system embodiments are basically similar to method embodiments, so the description is relatively simple; relevant parts can be referred to the descriptions in the method embodiments. In the description of this specification, the terms "one embodiment," "some embodiments," "example," "specific example," or "some examples," etc., refer to specific features, structures, materials, or characteristics described in connection with that embodiment or example, which are included in at least one embodiment or example of this specification. In this specification, the illustrative expressions of the above terms do not necessarily refer to the same embodiment or example. Furthermore, the specific features, structures, materials, or characteristics described can be combined in any suitable manner in one or more embodiments or examples. Moreover, without contradiction, those skilled in the art can combine and integrate the different embodiments or examples described in this specification and the features of different embodiments or examples.
[0093] The above description is merely an embodiment of one or more embodiments of this specification and is not intended to limit the scope of this specification. Various modifications and variations can be made to the one or more embodiments of this specification by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of this specification should be included within the scope of the claims.
Claims
1. A method for implementing a reflection mechanism in a blockchain, comprising: During the process of the compiler compiling the source code of a contract containing reflection programming into a Wasm file: The metadata of the first type and the metadata of the first function in the first type are generated based on the code defining the first type in the source code or bytecode, and the generated metadata is encapsulated in the Wasm file. The structure of the first function in the metadata of the first function includes: the number of method functions of the type, the index of the function in the function table, the linear memory address of the function name string, the linear memory address of the function return type, the number of parameters of the function, and the linear memory address of the type array of each parameter. The contract bytecode of the second function is generated based on the reflection function code in the source code. The second function is used to obtain the type and content of the first function based on the dynamic parameters at runtime. Upon receiving a transaction requesting the invocation of a contract, the virtual machine loads the Wasm file of the invoked contract and: Create a linear memory region; At least a portion of the memory in the linear memory region is initialized using the metadata in the Wasm file; The contract bytecode in the Wasm file is parsed and executed. When the bytecode of the second function is executed, the first function to be called is determined and executed in the linear memory area based on the function name string of the function called in the transaction of the calling contract and the metadata.
2. The method as described in claim 1, wherein the meta-information includes the structure of the first type of object and the structure of the first function.
3. The method as described in claim 2, wherein the structure of the first type of object in the metadata includes: The linear memory address of an object type; The linear memory addresses of the array of fields of the object.
4. The method as described in claim 2, wherein the metadata further includes a first type structure or a first type field structure.
5. The method of claim 4, wherein the first type structure in the metadata includes: The linear memory address of the type name string; The linear memory address of an array of fields of type; The linear memory address of an array of methods and functions of type [type].
6. The method as described in claim 4, wherein the field structure of the first type in the metadata includes: Number of fields in the type; The linear memory address of the field name string; The linear memory address of the field's return type.
7. The method as described in claim 1, The step of generating the contract bytecode for the second function based on the reflection functionality code in the source code includes: Based on the reflection library imported in the source code, the contract bytecode of the second function is generated according to the reflection function code in the source code.
8. The method of claim 1, wherein after the virtual machine loads the Wasm file of the invoked contract, it further includes creating a normal memory region.
9. The method of claim 8, wherein the virtual machine initializes at least a portion of the ordinary memory using first function bytecode and second function bytecode contained in the Wasm file.
10. The method of claim 9, wherein initializing at least a portion of the ordinary memory using the first function bytecode and the second function bytecode contained in the Wasm file comprises: A function table and function code are generated in the ordinary memory, wherein the function table stores the starting address of the memory where the function code is located.
11. A compilation method in which the compiler compiles the source code of a contract containing reflection programming into a Wasm file: Based on the code defining the first type in the source code or bytecode, generate metadata of the first type and metadata of the first function in the first type, and encapsulate the generated metadata in the Wasm file. The structure of the first function in the metadata of the first function includes: The number of methods / functions of a type, the index of a function in the function table, the linear memory address of the function name string, the linear memory address of the function return type, the number of parameters of the function, and the linear memory address of the array of types of each parameter; The contract bytecode of the second function is generated based on the reflection function code in the source code. The second function is used to obtain the type and content of the first function based on the dynamic parameters at runtime. Upon receiving a transaction requesting the invocation of a contract, the virtual machine loads the Wasm file of the invoked contract and: Create a linear memory region; At least a portion of the memory in the linear memory region is initialized using the metadata in the Wasm file; The contract bytecode in the Wasm file is parsed and executed. When the bytecode of the second function is executed, the first function to be called is determined and executed in the linear memory area based on the function name string of the function called in the transaction of the calling contract and the metadata.
12. The method of claim 11, further comprising creating a general memory region and initializing at least a portion of the general memory using first function bytecode and second function bytecode contained in a Wasm file.
13. The method of claim 12, wherein initializing at least a portion of the ordinary memory using the first function bytecode and the second function bytecode contained in the Wasm file comprises: A function table and function code are generated in the ordinary memory, wherein the function table stores the starting address of the memory where the function code is located.
14. An apparatus comprising a compiler and a Wasm virtual machine, wherein, The compiler includes: The meta-information generation unit is used to generate meta-information of the first type and meta-information of the first function in the first type based on the code that defines the first type in the source code or bytecode. The structure of the first function in the meta-information of the first function includes: the number of method functions of the type, the index of the function in the function table, the linear memory address of the function name string, the linear memory address of the function return type, the number of parameters of the function, and the linear memory address of the type array of each parameter. An encapsulation unit is used to encapsulate the metadata generated by the metadata generation unit in a Wasm file; The second function contract bytecode generation unit is used to generate the contract bytecode of the second function based on the reflection function code in the source code. The second function is used to obtain the first function type and the first function content based on the dynamic parameters at runtime. The Wasm virtual machine includes: The loading unit is used to load the Wasm file of the invoked contract; Create a unit, used to create a linear memory region; The first initialization unit initializes at least a portion of the memory in the linear memory region using the metadata in the Wasm file; The execution unit parses and executes the contract bytecode in the Wasm file, and when executing the bytecode of the second function, it determines the first function to be called in the linear memory area based on the meta-information according to the function name string of the function called in the transaction that calls the contract, and executes it.
15. A blockchain node device for executing smart contracts, the node device comprising the Wasm virtual machine of claim 14, or the node device being used to execute the method of any one of claims 11-13.
16. A blockchain node device for executing smart contracts, comprising: processor, A memory storing a program, wherein when the processor executes the program, the method of any one of claims 11-13 is implemented.
Citation Information
Patent Citations
Method and device for deploying and executing intelligent contracts
CN110675256A
Smart execution method, engine and block chain node
CN113688186A
Method and a software product for adapting a .NET framework compliant reflection mechanism to a java environment
US20060143597A1
