Introduction to Bitcoin Smart Contract (2)-Introduction to the high-level language sCrypt

Script mystery

In the previous article, we briefly introduced the operating basis of Bitcoin smart contracts, that is, the underlying scripting language Script of the Bitcoin network and the operating principle of its virtual machine. I believe that many students who are in contact for the first time will have some confusion after reading it: How does this thing look nothing like scripting languages ​​like Python and JavaScript that everyone is usually familiar with? How to learn and use the scripting language of "the skeleton is so amazing"? With these questions, let's talk more deeply.

Why Script?

As we all know, the Bitcoin network is essentially a set of public ledger run and maintained by many miner nodes. All nodes need to ensure that the data on this ledger is legal and accurate. In other words, any transaction can be broadcast and verified by any node. The miner actually needs to run the script to check whether the "key" provided in the new transaction can "open" the "lock" in the old transaction. , In order to verify the legality of the transaction. In the verification process, the advantages of Script are reflected in these two aspects:

  • No need to compile, execute efficient : due Script Script code is a string of bytes 1 , before the need to compile the virtual machine process again, in order to explain the results obtained can be directly executed instruction, thus ensuring the efficiency.

  • Design security and prevent attacks : A very big feature of Script is that there is no jump instruction, which can prevent someone from maliciously (or negligently) writing an endless loop in the script to attack the miner network. This is often criticized as Turing's incompleteness, unable to achieve many functions. But in fact, this is a misunderstanding. Turing completeness can be achieved through some technical means (follow-up, I plan to write another article to talk about this).

However, Script is not so friendly to developers. There are very high thresholds for learning, development and testing, because it is essentially an assembly language.

High-level language (sCrypt) vs assembly language (Script)

I believe that most students who have studied assembly language have similar memories: remember to learn it in school! That's it, most people will never encounter it in actual projects. For students who are not familiar with assembly language, you may only need to know that it is a programming language that was born in the early days of computer invention. Writing programs in it is usually very complicated and time-consuming.

The sCrypt project came into being because of the inefficiency of Script language development like assembly language. Its goal is to provide developers with a more advanced development language and familiar development environment, thereby improving the overall R&D efficiency. Simply put, developers use the sCrypt language to develop smart contracts, and then use a compiler to convert the source code into Script scripting language and put them in the transaction to send on the chain. Finally, the miners ensure that the contract code runs correctly.

The following formally introduces the high-level development language of Bitcoin smart contracts: sCrypt (English pronunciation: ess crypt).

sCrypt basic syntax and structure

Syntax 2 of sCrypt was designed with the goal of minimizing the learning cost of developers, so it has many similarities with some other high-level languages ​​(such as Javascript, Solidity, etc.) as a whole, which is also intentional.

Basic data type

sCrypt is a strongly typed language. The basic data types include:

  • bool: Boolean value trueor false;

  • int: Signed integer value;

int a1 = 42;
int a2 = -4242424242424242;
int a3 = 55066263022277343669578718895168534326250603453777594175500187360389116729240;
int a4 = 0xFF8C;
  • bytes: Hexadecimal byte array representation, contained within the single quotation marks and letters bas a prefix;
bytes b1 = b'ffee1234';
bytes b2 = b'414136d08c5ed2bf3ba048afe6dcaebafeffffffffffffffffffffffffffffff00';

In order to further improve type safety, bytesit can also be converted to a more precise subtype description so that the compiler can find or reduce potential code errors. Specific types include:

  • PubKey: Public key type
PubKey pubKey = PubKey(b'0200112233445566778899aabbccddeeffffeeddccbbaa99887766554433221100');
  • SigHashType: Signature hash type
SigHashType s = SigHashType(b'01');
SigHashType s = SigHash.ALL | SigHash.ANYONECANPAY;
  • Sig: Signature type in DER format, which contains the signature hash type value;
Sig sig = Sig(b'3045022100b71be3f1dc001e0a1ad65ed84e7a5a0bfe48325f2146ca1d677cf15e96e8b80302206d74605e8234eae3d4980fcd7b2fdc1c5b9374f0ce71dea38707fccdbd28cf7e41');
  • Ripemd160: RIPEMD-160 hash type
Ripemd160 r = Ripemd160(b'0011223344556677889999887766554433221100');
  • Sha1: Sha1 hash type
Sha1 s = Sha1(b'0011223344556677889999887766554433221100');
  • Sha256: Sha256 hash type
Sha256 s = Sha256(b'00112233445566778899aabbccddeeffffeeddccbbaa99887766554433221100');
  • OpCodeType: Opcode numeric type
OpCode.OP_ADD // b'93'

Property variable (property)

Each contract may consist of several properties variables (i.e., object-oriented languages generally instance variables), the contract can be a function of the thisaccess key. Such as:

contract Test {
    
    
    int x;
    bool y;
    bytes z;
    ...
}

Constructor

Each contract has at most 1 constructor (if not, one will be automatically generated by the compiler), which is generally used to initialize attribute variables. Such as:

contract Test {
    
    
    constructor(int x) {
    
    
        this.x = x;
    }
    ...
}

Build-in functions

  • require(bool expr): When this function is called to check the parameter expression exprBoolean value results. If trueyou continue down; otherwise immediately interrupt execution process, contract execution failed. Equivalent to C/C++, Java, and python assert().

  • exit(bool status): This function is called immediately interrupt execution process, parameter statusvalue is truewhen the contract is executed successfully; otherwise the contract execution failed.

Public function

The public function is the interface for externally calling the contract. The main logic code contained in the function body can be regarded as the locking script; the function parameters can be regarded as the corresponding unlocking script. The miner actually verifies the execution result of this pair of combinations.

The particularities of this type of function are as follows:

  1. No explicit returnstype declarations and the end of the function returnstatement, which is invisible to return true;
  2. End of the function must be a require()function call;
  3. Only when the function ends, all running encountered require()have passed, the script is considered by check; otherwise deemed script check fails, which will cause the transaction to fail.
contract Test {
    
    
    public function equal(int y) {
    
    
        require(this.valueOf(y) == this.x);
    }
    ...
}

Non-public function (function)

Non-public functions can be regarded as private functions of the contract, whose main purpose is to encapsulate internal logic and code reuse. Need to be used when defining a keyword returnswill be described with the return type, such as:

contract Test {
    
    
    function valueOf(int x) returns(int) {
    
    
        return x;
    }
    ...
}

In addition to some of the content briefly introduced above, the complete official documentation containing some other language features can be viewed here (in continuous iterative update).

sCrypt contract example

Finally, look at this complete sCrypt contract (it should be easy to understand):

contract Test {
    
      // 定义合约 
    int x;  // 属性变量

    constructor(int x) {
    
      // 定义构造函数
        this.x = x;  // 初始化属性变量值
    }

    public function equal(int y) {
    
      // 定义公共函数,解锁参数 y 为 int 类型
        require(this.valueOf(y) == this.x);  // 调用 require 函数,只有参数表达式值为 true 时,合约才能执行成功
    }
    
    function valueOf(int x) returns (int) {
    
       // 定义内部函数
        return x;		// 返回值
    }
}

In the following articles, I will continue to introduce sCrypt-related development tools and some more complex contract design and implementation. If you are interested, please continue to pay attention:)

appendix


  1. Script Operation Code (Opcode) Complete Works↩︎

  2. sCrypt official document ↩︎

Guess you like

Origin blog.csdn.net/freedomhero/article/details/107104952