[software engineering application and practice] JDchain smart contract quick start

Posted by social_experiment on Sat, 01 Jan 2022 08:30:28 +0100

Smart contract

1. Introduction

JD Chain intelligent contract system consists of five parts: contract code language, contract engine, contract account, contract development framework and contract development plug-in.

Contract code language is a programming language used to write smart contracts. Contract engine is a virtual machine that interprets and executes contract code.

The JD Chain ledger manages contract codes in the form of contract accounts. A contract code for deploying the uplink needs to be associated with a unique public key, generate the blockchain account address corresponding to the public key, and register it as a contract account in the account book. Before execution, the system reads the contract code from the ledger and loads it into the contract engine. The transaction executor calls the contract engine to trigger contract execution.

JD Chain ledger defines a set of standard ledger operation instructions. The execution process of contract code is essentially to output a series of operation instruction sequences to the ledger. These instructions change the data in the ledger and form the final result of contract execution.

The contract development framework defines a set of programming interfaces and class libraries that need to be relied on in contract code development. The contract development plug-in provides a contract compilation and deployment tool that is more convenient to integrate with the IDE, which can simplify the operation and be combined with the continuous integration process.

JD Chain takes Java language as the contract code language, and the contract engine is a security sandbox built based on JVM. In order to achieve seamless compatibility with mainstream application development methods, JD Chain supports engineering projects with Maven to manage contract code, and provides corresponding Maven plug-ins to simplify contract compilation and deployment.

Smart contract is a kind of contract / protocol that can be executed by computer. Unlike contracts in real life, which are written in natural language and stipulate the rights and obligations of relevant parties, smart contracts are written in contract code language and exist and executed in the form of contract code. The data status in the ledger is used to represent the relevant terms of the contract / agreement. The operation process of the contract code reflects the implementation of the terms of the contract / agreement, and records the corresponding results.

2. Quick start

2.1. Prepare development environment

Prepare according to the requirements of normal Java application development environment, and take Maven as the construction management tool of code engineering. There are no other special requirements.

Check that the JDK version is not lower than 1.8 and Maven version is not lower than 3.0.

2.2. Create Contract Code Project

Create a normal Java Maven project and open POM XML set packaging to contract

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>your.group.id</groupId>
  <artifactId>your.project</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <!-- It is declared as a contract code project, and the compilation output extension is".car"Contract code -->
  <packaging>contract</packaging>

  <dependencies>
     <!-- Reliance on contract items -->
  </dependencies>

  <build>
     <plugins>
        <!-- Plug ins for contract items -->
     </plugins>
  </build>
</project>

2.3. Join contract development dependency

In the contract code project POM XML adds dependency on contract development SDK:

<dependency>
   <groupId>com.jd.blockchain</groupId>
   <artifactId>contract-starter</artifactId>
   <version>${jdchain.version}</version>
</dependency>

2.4. Add contract plugin

In the contract code project POM Add contract Maven plugin to XML:

<plugin>
  <groupId>com.jd.blockchain</groupId>
  <artifactId>contract-maven-plugin</artifactId>
  <version>${jdchain.version}</version>
  <extensions>true</extensions>
</plugin>

Complete POM The XML is as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>your.group.id</groupId>
 <artifactId>your.project</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <!-- It is declared as a contract code project, and the compilation output extension is".car"Contract code -->
 <packaging>contract</packaging>

 <properties>
    <jdchain.version>1.4.2.RELEASE</jdchain.version>
 </properties>
 
 <dependencies>
    <!-- Reliance on contract items -->
    <dependency>
       <groupId>com.jd.blockchain</groupId>
       <artifactId>contract-starter</artifactId>
       <version>${jdchain.version}</version>
    </dependency>
 </dependencies>

 <build>
    <plugins>
       <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>3.8.1</version>
           <configuration>
               <source>1.8</source>
               <target>1.8</target>
               <encoding>UTF-8</encoding>
               <optimize>false</optimize>
               <debug>true</debug>
               <showDeprecation>false</showDeprecation>
               <showWarnings>false</showWarnings>
           </configuration>
       </plugin>

       <!-- Plug ins for contract items -->
       <plugin>
          <groupId>com.jd.blockchain</groupId>
          <artifactId>contract-maven-plugin</artifactId>
          <version>${jdchain.version}</version>
          <extensions>true</extensions>
       </plugin>
    </plugins>
 </build>
</project>

2.5. Write contract code

2.5. 1. Precautions

  1. Contracts (including contract interfaces and contract implementation classes) are not allowed to use package s starting with com.jd.blockchain;
  2. There must be and only one interface using @ Contract annotation, and the event must be greater than or equal to one;
  3. The interface annotated with @ Contract has only one implementation class;
  4. Blacklist call restrictions (see the configuration file for the specific blacklist). It should be noted that the blacklist analysis strategy will recursively analyze the interface and parent class implemented by the class, that is, calling a class that implements the specified blacklist interface is not allowed;

2.5. 2. Declaration of contract

/**
 * Declare the contract interface;
**/ 
@Contract
public interface AssetContract {

   @ContractEvent(name = "transfer")
   String transfer(String address, String from, String to, long amount);
   
}

2.5. 3. Realize the contract

/**
 * Realization of the contract;
 * 
 * It is optional to implement the EventProcessingAware interface to obtain the ContractEventContext context object,
 * Ledger operation can be performed through this object;
 */
public class AssetContractImpl implements AssetContract, EventProcessingAware {
   
   // Contract event context;
   private ContractEventContext eventContext;

   /**
    * Execute the transfer call to AssetContract contract in the transaction request;
    */
   public String transfer(String address, String from, String to, long amount) {
      //Hash of the current ledger;
      HashDigest ledgerHash = eventContext.getCurrentLedgerHash();
      //Current ledger context;
      LedgerContext ledgerContext = eventContext.getLedger();

      //Operation;
      // ledgerContext.

      //Return the result of contract operation;
      return "success";
   }

   /**
    * Prepare to execute the contract call operation in the transaction;
    */
   @Override
   public void beforeEvent(ContractEventContext eventContext) {
      this.eventContext = eventContext;
   }

   /**
    * Complete the contract call operation in the execution transaction;
    */
   @Override
   public void postEvent(ContractEventContext eventContext, Exception error) {
      this.eventContext = null;
   }
}

Visible range of ledger data:

The getUncommittedLedger method in ContractEventContext can access the uncommitted block data in execution. The reasonable use of this method can solve the problem of data version / event sequence conflict involved in the concurrent call of contract methods by customers.

/**
 * Currently contains unsubmitted block data ledger query context;
 */
LedgerQueryService getUncommittedLedger();

The getLedger method in ContractEventContext accesses the latest block data submitted on the chain and does not contain uncommitted transactions. Therefore, the data between multiple contract method calls in uncommitted transactions is invisible, resulting in data version conflicts during concurrency.

/**
 * Ledger operation context;
 */
LedgerContext getLedger();

The ledger operation in the contract method can be referenced by calling the relevant methods in the LedgerContext Example contract

2.6. Compile and package contract code

The compilation and packaging operation of the contract code project is the same as that of the normal maven project. Enter the following command in the root directory of the project:

mvn clean package

After successful execution, output the contract code file < project name > in the target directory< version>. car .

If the contract code is added except com jd. Blockchain: dependencies other than contract starter. Under the default configuration, the third-party dependency package will be associated with car files are packaged and deployed together.

Topics: Blockchain Ethereum