1. 程式人生 > >幣幣合約執行解析(包含部分原始碼)

幣幣合約執行解析(包含部分原始碼)

比原專案倉庫:

本文解析的為比原提供的幣幣合約 模板如下:

contract TradeOffer(assetRequested: Asset,
                    amountRequested: Amount,
                    seller: Program,
                    cancelKey: PublicKey) locks offered {
  clause trade() requires payment: amountRequested of assetRequested {
    lock payment with seller
    unlock offered
  }
  clause cancel(sellerSig: Signature) {
    verify checkTxSig(cancelKey, sellerSig)
    unlock offered
  }
}

導讀:

初次接觸比原只能合約的請點選[比原智慧合約入門](https://bbs.bbug.org.cn/thread-26.htm)  和 [

鎖定合約

第一步:呼叫create-account-receiver 生成 control_program

圖片描述圖片描述

以下是相關程式碼片段:

sendHttpPost("{\"account_id\":\"0IJVD7MNG0A02\"}","create-account-receiver","http://127.0.0.1:9888","");

第二步呼叫list-pubkeys 獲取 pubkey

圖片描述圖片描述

以下是相關程式碼片段:

sendHttpPost("{\"account_id\":\"0IJVD7MNG0A02\"}","list-pubkeys","http://127.0.0.1:9888","");

第三步: 將1 2步獲取的值呼叫compile介面編譯合約獲得program 合約程式

圖片描述圖片描述

以下是相關程式碼片段:

            JSONObject param=new JSONObject();
            JSONArray agrs=new JSONArray();
            //合約的四個引數值
            JSONObject assetParam=new JSONObject();
            assetParam.put("string","81d097312645696daea84b761d2898d950d8fba0de06c9267d8513b16663dd3a");
            agrs.put(assetParam);
            JSONObject amountParam=new JSONObject();
            amountParam.put("integer",200000000l);
            agrs.put(amountParam);
            JSONObject programParam=new JSONObject();
            programParam.put("string",control_program);
            agrs.put(programParam);
            JSONObject publicKeyParam=new JSONObject();
            publicKeyParam.put("string",pubkey);
            agrs.put(publicKeyParam);
            param.put("agrs",agrs);
            param.put("contract","contract TradeOffer(assetRequested: Asset, amountRequested: Amount, seller: Program, cancelKey: PublicKey) locks offered { clause trade() requires payment: amountRequested of assetRequested { lock payment with seller unlock offered } clause cancel(sellerSig: Signature) { verify checkTxSig(cancelKey, sellerSig) unlock offered } }");
            //呼叫編譯合約
            sendHttpPost(param.toString(),"list-pubkeys","http://127.0.0.1:9888","");

第四步:將program 傳入build-transaction介面去build一個交易的到data

圖片描述圖片描述

以下是相關程式碼片段:

            param=new JSONObject();
            agrs=new JSONArray();
            JSONObject spendAccount=new JSONObject();
            spendAccount.put("account_id","0H757LPD00A02");
            spendAccount.put("amount",9909099090000l);
            spendAccount.put("asset_id","161b9767b664df907fa926a31f9e835236e57f3e9ccc5f80c12bd97723322652");
            spendAccount.put("type","spend_account");
            agrs.put(spendAccount);
            JSONObject controlAccount=new JSONObject();
            controlAccount.put("control_program",program);
            controlAccount.put("amount",9909099090000l);
            controlAccount.put("asset_id","161b9767b664df907fa926a31f9e835236e57f3e9ccc5f80c12bd97723322652");
            controlAccount.put("type","control_program");
            agrs.put(controlAccount);
            JSONObject spendAccount2=new JSONObject();
            spendAccount2.put("account_id","0H757LPD00A02");
            spendAccount2.put("amount",6000000l);
            spendAccount2.put("asset_id","ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
            spendAccount2.put("type","spend_account");
            agrs.put(spendAccount2);
            param.put("actions",agrs);
            param.put("ttl",0);
            sendHttpPost(param.toString(),"build-transaction","http://127.0.0.1:9888","");

第五步:輸入密碼呼叫sign-transaction簽名第四步build的data 得到raw_transaction

圖片描述圖片描述

以下是相關程式碼片段:

            param=new JSONObject();
            param.put("password","xxx");
            param.put("transaction",data);
            sendHttpPost(param.toString(),"sign-transaction","http://127.0.0.1:9888","");

第六步:呼叫submit-transactions提交交易

圖片描述

以下是相關程式碼片段:

            param=new JSONObject();
            param.put("raw_transaction",raw_transaction);
            sendHttpPost(param.toString(),"submit-transactions","http://127.0.0.1:9888","");

解鎖/取消合約

首先需要decode出生成合約時候的引數

呼叫list-unspent-outputs 獲取生成的合約資訊獲取program

圖片描述

以下是相關程式碼片段:

param=new JSONObject();
        param.put("id",outputid);
        param.put("smart_contract",true);
        sendHttpPost(param.toString(),"list-unspent-outputs","http://127.0.0.1:9888","");

呼叫decode-program 傳入獲取生成的合約引數資訊

圖片描述以下是相關程式碼片段:

param=new JSONObject();
        param.put("program",program);
        sendHttpPost(param.toString(),"decode-program","http://127.0.0.1:9888","");

需要注意的是decode出來的為值是逆序的(後續會有文章詳細介紹)

解鎖/取消其實就是把生成合約的步驟中的第三步去掉,替換呼叫生成合約第四步的引數即可

取消合約的構造引數如下:圖片描述

                spendAccountUnspentOutput = arguments: [{
                  type: 'raw_tx_signature',
                  // 生成合約第二步的pubkeylist 詳情
                  raw_data: {
                    derivation_path: pubkeylist.pubkey_infos[0].derivation_path,
                    xpub: pubkeylist.root_xpub
                  }
                }, {
                  type: 'data',
                  raw_data: {
                    // 引數偏移量 在一個合約裡是固定的 
                    value: '13000000'
                  }
                }],
                output_id: output_id,
                type: 'spend_account_unspent_output'
              }
              const controlAction = {
                type: 'control_program',
                amount: 100000000,
                asset_id: asset_id,
                control_program:control_program
              }
              const gasAction = {
                type: 'spend_account',
                account_id:account_id,
                asset_alias: 'BTM',
                amount: 50000000
              }

執行合約的引數構造如下:圖片描述

           const spendAccountUnspentOutput = {
                arguments: [{
                  type: 'data',
                  raw_data: {
                    // 執行合約輸入資產偏移量
                    value: '00000000'
                  }
                }],
                output_id: output_id,
                type: 'spend_account_unspent_output'
              }
              // 合約執行提供的資產
              const issueControlAction = {
                control_program: control_program,
                amount:  100000000,
                asset_id: asset_id,
                type: 'control_program'
              }
              // 合約執行提供的資產
              const issueSpendAction = {
                account_id: account_id,
                amount: 100000000,
                asset_id: asset_id,
                type: 'spend_account'
              }
              // 曠工費
              const gasAction = {
                type: 'spend_account',
                account_id: account_id,
                asset_alias: 'BTM',
                amount: 50000000
              }
              // 合約執行獲得資產物件
              const controlAction = {
                type: 'control_program',
                amount:  100000000,
                asset_id: asset_id,
                control_program: compileData.control_program
              }

build 操作其實就是指定輸入輸出的過程,詳情請檢視 官方build文件官方api文件

備註

呼叫比原基於okhttp介面javautil 如下:

    public static String sendHttpPost(String bodyStr,String method,String bytomApiserverUrl,String bytomApiserverToken) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyStr);
        Request request = new Request.Builder()
                .url(bytomApiserverUrl+"/"+method)
                .post(body)
                .addHeader("cache-control", "no-cache")
                .addHeader("Connection", "close")
                .build();
        if (bytomApiserverUrl==null || bytomApiserverUrl.contains("127.0.0.1") || bytomApiserverUrl.contains("localhost")){

        }else {
            byte[] encodedAuth = Base64.encodeBase64(bytomApiserverToken.getBytes(Charset.forName("US-ASCII")));
            String authHeader = "Basic " + new String(encodedAuth);
            request = new Request.Builder()
                    .url(bytomApiserverUrl+"/"+method)
                    .post(body)
                    .addHeader("authorization", authHeader)
                    .addHeader("cache-control", "no-cache")
                    .addHeader("Connection", "close")
                    .build();
        }
        Response response = client.newCall(request).execute();
        return response.body().string();
    }