【以太坊系列-009】在ethereum private chain上进行oraclize的调用操作

说明:

     本人使用的是 ubuntu1804-server版本(不要使用live-server,存在缺少部分包。)
     在私链中容易遇到问题,本人第一次成功是通过truffle+ethereumjs-testrpc。
     私链上不熟悉的人,操作会比较麻烦,容易出问题,并且文档比较少。
     本文只是记录oraclize环境的搭建,更多请参阅官网。(更多搭建请参照该系列其余文档)

一、ethereum 私链准备

前置:
    环境信息,具体环境搭建见该系列文档
    geth: 1.8.19-unstable
    go version: go1.10.3

操作:

1, mkdir -p /home/constantinople_data
2, cd /home/constantinople_data

# cat genesis.json 
{ 
    "config": {
                "chainId": 22, 
                "constantinopleBlock": 0,     #必须使用君士坦丁堡或者拜占庭之后的版本,
                                              #否则oraclise会缺少RETURNDATASIZE的指令而报错
                                              #(invalid opcode 0x3d)
                "eip155Block": 0, 
                "eip158Block": 0 
               },
    "alloc" : {},
    "coinbase" : "0x0000000000000000000000000000000000000000", 
    "difficulty" : "0x400", 
    "extraData" : "", 
    "gasLimit" : "0xffffffff", 
    "nonce" : "0x0000000000000038", 
    "mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000", 
    "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000", 
    "timestamp" : "0x00" 
}

3, 初始化
# geth --datadir /home/constantinople_data  init /home/constantinople_data/genesis.json

4, 启动
nohup geth --identity "TestNode" --rpc --rpcport "8545" --datadir /home/constantinople_data/ --port "30303" --rpccorsdomain "*" --dev.period 1 --nodiscover --debug --vmdebug --verbosity 5  &

5, 使用geth 登录
geth attach --datadir /home/constantinople_data/

6, 创建账户
personal.newAccount("lyh000")
personal.newAccount("lyh001")
personal.newAccount("lyh002")
personal.newAccount("lyh003")

7, 解锁账户
personal.unlockAccount(eth.accounts[0], "lyh000", 0) # 0表示永久解锁
personal.unlockAccount(eth.accounts[1], "lyh001", 0)
personal.unlockAccount(eth.accounts[2], "lyh002", 0)
personal.unlockAccount(eth.accounts[3], "lyh003", 0)

8,启动挖矿
miner.start(1); admin.sleepBlocks(5); miner.stop()  #挖5个矿

9, 转账,给每个账号设置一点余额
eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[1], value: web3.toWei(3, "ether")})
eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[2], value: web3.toWei(3, "ether")})
eth.sendTransaction({from: eth.accounts[0], to: eth.accounts[3], value: web3.toWei(3, "ether")})

10, 查看余额
> eth.getBalance(eth.accounts[0])
3000000000000000000
> eth.getBalance(eth.accounts[1])
3000000000000000000
> eth.getBalance(eth.accounts[2])
3000000000000000000
> eth.getBalance(eth.accounts[3])
3000000000000000000
web3.fromWei(eth.getBalance(eth.accounts[0]),"ether")
web3.fromWei(eth.getBalance(eth.accounts[1]),"ether")
web3.fromWei(eth.getBalance(eth.accounts[2]),"ether")
web3.fromWei(eth.getBalance(eth.accounts[3]),"ether")

二、ethereum-bridge 准备

1,安装

ethereum-bridge环境的准备
apt-get install nodejs
apt-get install npm 
npm install -g ethereum-bridge

node: v8.10.0 
npm: 3.5.2
ethereum-bridge: v0.6.1

2,启动 ethereum-bridge 
# ethereum-bridge -H localhost:8545 -a 1 
(在部署的过程中,需要在geth控制台中启动挖矿,因为ethereum-bridge中需要部署合约)
-a 表示使用的标号为1的账号,并且需要在geth控制台中把账号1解锁
personal.unlockAccount(eth.accounts[1], "lyh001", 0) 
部署好后,效果如下所示,如果该环境之前没部署过,不需要改oraclise代码,否则需要修改。
就是在合约的构造器中添加
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); 
这种代码。

# ethereum-bridge -H localhost:8545 -a 1 
Please wait...
[2018-11-27T05:56:14.967Z] INFO you are running ethereum-bridge - version: 0.6.1
[2018-11-27T05:56:14.969Z] INFO saving logs to: ./bridge.log
[2018-11-27T05:56:14.970Z] INFO using active mode
[2018-11-27T05:56:14.971Z] INFO Connecting to eth node http://localhost:8545
[2018-11-27T05:56:18.654Z] INFO connected to node type Geth/TestNode/v1.8.18-stable-58632d44/linux-amd64/go1.10.4
[2018-11-27T05:56:20.536Z] WARN Using 0x4fcc0e3f1fd03e2423137f0b342cc563dd37df42 to query contracts on your blockchain, make sure it is unlocked and do not use the same address to deploy your contracts
[2018-11-27T05:56:21.002Z] INFO deploying the oraclize connector contract...
[2018-11-27T05:56:44.676Z] INFO connector deployed to: 0x1dc7417ed01ee86771e079d47d980a59de309d58
[2018-11-27T05:56:45.221Z] INFO deploying the address resolver with a deterministic address...
[2018-11-27T05:57:40.979Z] INFO address resolver (OAR) deployed to: 0x6f485c8bf6fc43ea212e93bbf8ce046c7f1cb475
[2018-11-27T05:57:40.980Z] INFO updating connector pricing...
[2018-11-27T05:58:40.136Z] INFO successfully deployed all contracts
[2018-11-27T05:58:40.140Z] INFO instance configuration file saved to /usr/local/lib/node_modules/ethereum-bridge/config/instance/oracle_instance_20181127T005840.json
[2018-11-27T05:58:40.141Z] INFO you are using a deterministic OAR, you don't need to update your contract
[2018-11-27T05:58:40.723Z] INFO Listening @ 0x1dc7417ed01ee86771e079d47d980a59de309d58 (Oraclize Connector)
(Ctrl+C to exit)
# 如果已经部署过了,可以使用
ethereum-bridge --instance latest 

2, 此时可以看到eth.accounts[1]账户的余额减少
> web3.fromWei(eth.getBalance(eth.accounts[1]),"ether")
2.887187366999999999
> web3.fromWei(eth.getBalance(eth.accounts[0]),"ether")
23.10751858

三、部署自己写的调用oraclize合约

1, 设置基本账户
eth.coinbase=eth.accounts[0]
eth.defaultAccount=eth.accounts[0]
2, 合约代码
本文使用的是
https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.25.sol 
代码,只是把自己的代码集成到同一个文件而已
合约编译使用的是
http://remix.ethereum.org/#optimize=false&version=soljson-v0.4.25+commit.59dbf8f1.js

// <ORACLIZE_API>
// Release targetted at solc 0.4.25 to silence compiler warning/error messages, compatible down to 0.4.22
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD



Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:



The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.



THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

// This api is currently targeted at 0.4.22 to 0.4.25 (stable builds), please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary

pragma solidity >=0.4.22;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version

contract OraclizeI {
    address public cbAddress;
    function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
    function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
    function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
    function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
    function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
    function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
    function getPrice(string _datasource) public returns (uint _dsprice);
    function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
    function setProofType(byte _proofType) external;
    function setCustomGasPrice(uint _gasPrice) external;
    function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}

contract OraclizeAddrResolverI {
    function getAddress() public returns (address _addr);
}

/*
Begin solidity-cborutils

https://github.com/smartcontractkit/solidity-cborutils

MIT License

Copyright (c) 2018 SmartContract ChainLink, Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */

library Buffer {
    struct buffer {
        bytes buf;
        uint capacity;
    }

    function init(buffer memory buf, uint _capacity) internal pure {
        uint capacity = _capacity;
        if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
        // Allocate space for the buffer data
        buf.capacity = capacity;
        assembly {
            let ptr := mload(0x40)
            mstore(buf, ptr)
            mstore(ptr, 0)
            mstore(0x40, add(ptr, capacity))
        }
    }

    function resize(buffer memory buf, uint capacity) private pure {
        bytes memory oldbuf = buf.buf;
        init(buf, capacity);
        append(buf, oldbuf);
    }

    function max(uint a, uint b) private pure returns(uint) {
        if(a > b) {
            return a;
        }
        return b;
    }

    /**
     * @dev Appends a byte array to the end of the buffer. Resizes if doing so
     *      would exceed the capacity of the buffer.
     * @param buf The buffer to append to.
     * @param data The data to append.
     * @return The original buffer.
     */
    function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
        if(data.length + buf.buf.length > buf.capacity) {
            resize(buf, max(buf.capacity, data.length) * 2);
        }

        uint dest;
        uint src;
        uint len = data.length;
        assembly {
            // Memory address of the buffer data
            let bufptr := mload(buf)
            // Length of existing buffer data
            let buflen := mload(bufptr)
            // Start address = buffer address + buffer length + sizeof(buffer length)
            dest := add(add(bufptr, buflen), 32)
            // Update buffer length
            mstore(bufptr, add(buflen, mload(data)))
            src := add(data, 32)
        }

        // Copy word-length chunks while possible
        for(; len >= 32; len -= 32) {
            assembly {
                mstore(dest, mload(src))
            }
            dest += 32;
            src += 32;
        }

        // Copy remaining bytes
        uint mask = 256 ** (32 - len) - 1;
        assembly {
            let srcpart := and(mload(src), not(mask))
            let destpart := and(mload(dest), mask)
            mstore(dest, or(destpart, srcpart))
        }

        return buf;
    }

    /**
     * @dev Appends a byte to the end of the buffer. Resizes if doing so would
     * exceed the capacity of the buffer.
     * @param buf The buffer to append to.
     * @param data The data to append.
     * @return The original buffer.
     */
    function append(buffer memory buf, uint8 data) internal pure {
        if(buf.buf.length + 1 > buf.capacity) {
            resize(buf, buf.capacity * 2);
        }

        assembly {
            // Memory address of the buffer data
            let bufptr := mload(buf)
            // Length of existing buffer data
            let buflen := mload(bufptr)
            // Address = buffer address + buffer length + sizeof(buffer length)
            let dest := add(add(bufptr, buflen), 32)
            mstore8(dest, data)
            // Update buffer length
            mstore(bufptr, add(buflen, 1))
        }
    }

    /**
     * @dev Appends a byte to the end of the buffer. Resizes if doing so would
     * exceed the capacity of the buffer.
     * @param buf The buffer to append to.
     * @param data The data to append.
     * @return The original buffer.
     */
    function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
        if(len + buf.buf.length > buf.capacity) {
            resize(buf, max(buf.capacity, len) * 2);
        }

        uint mask = 256 ** len - 1;
        assembly {
            // Memory address of the buffer data
            let bufptr := mload(buf)
            // Length of existing buffer data
            let buflen := mload(bufptr)
            // Address = buffer address + buffer length + sizeof(buffer length) + len
            let dest := add(add(bufptr, buflen), len)
            mstore(dest, or(and(mload(dest), not(mask)), data))
            // Update buffer length
            mstore(bufptr, add(buflen, len))
        }
        return buf;
    }
}

library CBOR {
    using Buffer for Buffer.buffer;

    uint8 private constant MAJOR_TYPE_INT = 0;
    uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
    uint8 private constant MAJOR_TYPE_BYTES = 2;
    uint8 private constant MAJOR_TYPE_STRING = 3;
    uint8 private constant MAJOR_TYPE_ARRAY = 4;
    uint8 private constant MAJOR_TYPE_MAP = 5;
    uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;

    function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
        if(value <= 23) {
            buf.append(uint8((major << 5) | value));
        } else if(value <= 0xFF) {
            buf.append(uint8((major << 5) | 24));
            buf.appendInt(value, 1);
        } else if(value <= 0xFFFF) {
            buf.append(uint8((major << 5) | 25));
            buf.appendInt(value, 2);
        } else if(value <= 0xFFFFFFFF) {
            buf.append(uint8((major << 5) | 26));
            buf.appendInt(value, 4);
        } else if(value <= 0xFFFFFFFFFFFFFFFF) {
            buf.append(uint8((major << 5) | 27));
            buf.appendInt(value, 8);
        }
    }

    function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
        buf.append(uint8((major << 5) | 31));
    }

    function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
        encodeType(buf, MAJOR_TYPE_INT, value);
    }

    function encodeInt(Buffer.buffer memory buf, int value) internal pure {
        if(value >= 0) {
            encodeType(buf, MAJOR_TYPE_INT, uint(value));
        } else {
            encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
        }
    }

    function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
        encodeType(buf, MAJOR_TYPE_BYTES, value.length);
        buf.append(value);
    }

    function encodeString(Buffer.buffer memory buf, string value) internal pure {
        encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
        buf.append(bytes(value));
    }

    function startArray(Buffer.buffer memory buf) internal pure {
        encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
    }

    function startMap(Buffer.buffer memory buf) internal pure {
        encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
    }

    function endSequence(Buffer.buffer memory buf) internal pure {
        encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
    }
}

/*
End solidity-cborutils
 */

contract usingOraclize {
    uint constant day = 60*60*24;
    uint constant week = 60*60*24*7;
    uint constant month = 60*60*24*30;
    byte constant proofType_NONE = 0x00;
    byte constant proofType_TLSNotary = 0x10;
    byte constant proofType_Ledger = 0x30;
    byte constant proofType_Android = 0x40;
    byte constant proofType_Native = 0xF0;
    byte constant proofStorage_IPFS = 0x01;
    uint8 constant networkID_auto = 0;
    uint8 constant networkID_mainnet = 1;
    uint8 constant networkID_testnet = 2;
    uint8 constant networkID_morden = 2;
    uint8 constant networkID_consensys = 161;

    OraclizeAddrResolverI OAR;

    OraclizeI oraclize;
    modifier oraclizeAPI {
        if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
            oraclize_setNetwork(networkID_auto);

        if(address(oraclize) != OAR.getAddress())
            oraclize = OraclizeI(OAR.getAddress());

        _;
    }
    modifier coupon(string code){
        oraclize = OraclizeI(OAR.getAddress());
        _;
    }

    function oraclize_setNetwork(uint8 networkID) internal returns(bool){
      return oraclize_setNetwork();
      networkID; // silence the warning and remain backwards compatible
    }
    function oraclize_setNetwork() internal returns(bool){
        if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
            OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
            oraclize_setNetworkName("eth_mainnet");
            return true;
        }
        if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
            OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
            oraclize_setNetworkName("eth_ropsten3");
            return true;
        }
        if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
            OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
            oraclize_setNetworkName("eth_kovan");
            return true;
        }
        if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
            OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
            oraclize_setNetworkName("eth_rinkeby");
            return true;
        }
        if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
            OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
            return true;
        }
        if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
            OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
            return true;
        }
        if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
            OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
            return true;
        }
        return false;
    }

    function __callback(bytes32 myid, string result) public {
        __callback(myid, result, new bytes(0));
    }
    function __callback(bytes32 myid, string result, bytes proof) public {
      return;
      // Following should never be reached with a preceding return, however
      // this is just a placeholder function, ideally meant to be defined in
      // child contract when proofs are used
      myid; result; proof; // Silence compiler warnings
      oraclize = OraclizeI(0); // Additional compiler silence about making function pure/view.
    }

    function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
        return oraclize.getPrice(datasource);
    }

    function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
        return oraclize.getPrice(datasource, gaslimit);
    }

    function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query.value(price)(0, datasource, arg);
    }
    function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query.value(price)(timestamp, datasource, arg);
    }
    function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
    }
    function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
    }
    function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query2.value(price)(0, datasource, arg1, arg2);
    }
    function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
    }
    function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
    }
    function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
    }
    function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN.value(price)(0, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN.value(price)(timestamp, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = stra2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        string[] memory dynargs = new string[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN.value(price)(0, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource);
        if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN.value(price)(timestamp, datasource, args);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
        uint price = oraclize.getPrice(datasource, gaslimit);
        if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
        bytes memory args = ba2cbor(argN);
        return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
    }
    function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](1);
        dynargs[0] = args[0];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](2);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](3);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](4);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        return oraclize_query(datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs);
    }
    function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(timestamp, datasource, dynargs, gaslimit);
    }
    function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
        bytes[] memory dynargs = new bytes[](5);
        dynargs[0] = args[0];
        dynargs[1] = args[1];
        dynargs[2] = args[2];
        dynargs[3] = args[3];
        dynargs[4] = args[4];
        return oraclize_query(datasource, dynargs, gaslimit);
    }

    function oraclize_cbAddress() oraclizeAPI internal returns (address){
        return oraclize.cbAddress();
    }
    function oraclize_setProof(byte proofP) oraclizeAPI internal {
        return oraclize.setProofType(proofP);
    }
    function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
        return oraclize.setCustomGasPrice(gasPrice);
    }

    function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
        return oraclize.randomDS_getSessionPubKeyHash();
    }

    function getCodeSize(address _addr) view internal returns(uint _size) {
        assembly {
            _size := extcodesize(_addr)
        }
    }

    function parseAddr(string _a) internal pure returns (address){
        bytes memory tmp = bytes(_a);
        uint160 iaddr = 0;
        uint160 b1;
        uint160 b2;
        for (uint i=2; i<2+2*20; i+=2){
            iaddr *= 256;
            b1 = uint160(tmp[i]);
            b2 = uint160(tmp[i+1]);
            if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
            else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
            else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
            if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
            else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
            else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
            iaddr += (b1*16+b2);
        }
        return address(iaddr);
    }

    function strCompare(string _a, string _b) internal pure returns (int) {
        bytes memory a = bytes(_a);
        bytes memory b = bytes(_b);
        uint minLength = a.length;
        if (b.length < minLength) minLength = b.length;
        for (uint i = 0; i < minLength; i ++)
            if (a[i] < b[i])
                return -1;
            else if (a[i] > b[i])
                return 1;
        if (a.length < b.length)
            return -1;
        else if (a.length > b.length)
            return 1;
        else
            return 0;
    }

    function indexOf(string _haystack, string _needle) internal pure returns (int) {
        bytes memory h = bytes(_haystack);
        bytes memory n = bytes(_needle);
        if(h.length < 1 || n.length < 1 || (n.length > h.length))
            return -1;
        else if(h.length > (2**128 -1))
            return -1;
        else
        {
            uint subindex = 0;
            for (uint i = 0; i < h.length; i ++)
            {
                if (h[i] == n[0])
                {
                    subindex = 1;
                    while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
                    {
                        subindex++;
                    }
                    if(subindex == n.length)
                        return int(i);
                }
            }
            return -1;
        }
    }

    function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
        bytes memory _ba = bytes(_a);
        bytes memory _bb = bytes(_b);
        bytes memory _bc = bytes(_c);
        bytes memory _bd = bytes(_d);
        bytes memory _be = bytes(_e);
        string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
        bytes memory babcde = bytes(abcde);
        uint k = 0;
        for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
        for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
        for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
        for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
        for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
        return string(babcde);
    }

    function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
        return strConcat(_a, _b, _c, _d, "");
    }

    function strConcat(string _a, string _b, string _c) internal pure returns (string) {
        return strConcat(_a, _b, _c, "", "");
    }

    function strConcat(string _a, string _b) internal pure returns (string) {
        return strConcat(_a, _b, "", "", "");
    }

    // parseInt
    function parseInt(string _a) internal pure returns (uint) {
        return parseInt(_a, 0);
    }

    // parseInt(parseFloat*10^_b)
    function parseInt(string _a, uint _b) internal pure returns (uint) {
        bytes memory bresult = bytes(_a);
        uint mint = 0;
        bool decimals = false;
        for (uint i=0; i<bresult.length; i++){
            if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
                if (decimals){
                   if (_b == 0) break;
                    else _b--;
                }
                mint *= 10;
                mint += uint(bresult[i]) - 48;
            } else if (bresult[i] == 46) decimals = true;
        }
        if (_b > 0) mint *= 10**_b;
        return mint;
    }

    function uint2str(uint i) internal pure returns (string){
        if (i == 0) return "0";
        uint j = i;
        uint len;
        while (j != 0){
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len - 1;
        while (i != 0){
            bstr[k--] = byte(48 + i % 10);
            i /= 10;
        }
        return string(bstr);
    }

    using CBOR for Buffer.buffer;
    function stra2cbor(string[] arr) internal pure returns (bytes) {
        safeMemoryCleaner();
        Buffer.buffer memory buf;
        Buffer.init(buf, 1024);
        buf.startArray();
        for (uint i = 0; i < arr.length; i++) {
            buf.encodeString(arr[i]);
        }
        buf.endSequence();
        return buf.buf;
    }

    function ba2cbor(bytes[] arr) internal pure returns (bytes) {
        safeMemoryCleaner();
        Buffer.buffer memory buf;
        Buffer.init(buf, 1024);
        buf.startArray();
        for (uint i = 0; i < arr.length; i++) {
            buf.encodeBytes(arr[i]);
        }
        buf.endSequence();
        return buf.buf;
    }

    string oraclize_network_name;
    function oraclize_setNetworkName(string _network_name) internal {
        oraclize_network_name = _network_name;
    }

    function oraclize_getNetworkName() internal view returns (string) {
        return oraclize_network_name;
    }

    function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
        require((_nbytes > 0) && (_nbytes <= 32));
        // Convert from seconds to ledger timer ticks
        _delay *= 10;
        bytes memory nbytes = new bytes(1);
        nbytes[0] = byte(_nbytes);
        bytes memory unonce = new bytes(32);
        bytes memory sessionKeyHash = new bytes(32);
        bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
        assembly {
            mstore(unonce, 0x20)
            // the following variables can be relaxed
            // check relaxed random contract under ethereum-examples repo
            // for an idea on how to override and replace comit hash vars
            mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
            mstore(sessionKeyHash, 0x20)
            mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
        }
        bytes memory delay = new bytes(32);
        assembly {
            mstore(add(delay, 0x20), _delay)
        }

        bytes memory delay_bytes8 = new bytes(8);
        copyBytes(delay, 24, 8, delay_bytes8, 0);

        bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
        bytes32 queryId = oraclize_query("random", args, _customGasLimit);

        bytes memory delay_bytes8_left = new bytes(8);

        assembly {
            let x := mload(add(delay_bytes8, 0x20))
            mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
            mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))

        }

        oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
        return queryId;
    }

    function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
        oraclize_randomDS_args[queryId] = commitment;
    }

    mapping(bytes32=>bytes32) oraclize_randomDS_args;
    mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;

    function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
        bool sigok;
        address signer;

        bytes32 sigr;
        bytes32 sigs;

        bytes memory sigr_ = new bytes(32);
        uint offset = 4+(uint(dersig[3]) - 0x20);
        sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
        bytes memory sigs_ = new bytes(32);
        offset += 32 + 2;
        sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);

        assembly {
            sigr := mload(add(sigr_, 32))
            sigs := mload(add(sigs_, 32))
        }


        (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
        if (address(keccak256(pubkey)) == signer) return true;
        else {
            (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
            return (address(keccak256(pubkey)) == signer);
        }
    }

    function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
        bool sigok;

        // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
        bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
        copyBytes(proof, sig2offset, sig2.length, sig2, 0);

        bytes memory appkey1_pubkey = new bytes(64);
        copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);

        bytes memory tosign2 = new bytes(1+65+32);
        tosign2[0] = byte(1); //role
        copyBytes(proof, sig2offset-65, 65, tosign2, 1);
        bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
        copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
        sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);

        if (sigok == false) return false;


        // Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
        bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";

        bytes memory tosign3 = new bytes(1+65);
        tosign3[0] = 0xFE;
        copyBytes(proof, 3, 65, tosign3, 1);

        bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
        copyBytes(proof, 3+65, sig3.length, sig3, 0);

        sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);

        return sigok;
    }

    modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
        // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
        require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));

        bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
        require(proofVerified);

        _;
    }

    function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
        // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
        if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;

        bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
        if (proofVerified == false) return 2;

        return 0;
    }

    function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
        bool match_ = true;

        require(prefix.length == n_random_bytes);

        for (uint256 i=0; i< n_random_bytes; i++) {
            if (content[i] != prefix[i]) match_ = false;
        }

        return match_;
    }

    function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){

        // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
        uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
        bytes memory keyhash = new bytes(32);
        copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
        if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;

        bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
        copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);

        // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
        if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;

        // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
        // This is to verify that the computed args match with the ones specified in the query.
        bytes memory commitmentSlice1 = new bytes(8+1+32);
        copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);

        bytes memory sessionPubkey = new bytes(64);
        uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
        copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);

        bytes32 sessionPubkeyHash = sha256(sessionPubkey);
        if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){ //unonce, nbytes and sessionKeyHash match
            delete oraclize_randomDS_args[queryId];
        } else return false;


        // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
        bytes memory tosign1 = new bytes(32+8+1+32);
        copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
        if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;

        // verify if sessionPubkeyHash was verified already, if not.. let's do it!
        if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
            oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
        }

        return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
    }

    // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
    function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
        uint minLength = length + toOffset;

        // Buffer too small
        require(to.length >= minLength); // Should be a better way?

        // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
        uint i = 32 + fromOffset;
        uint j = 32 + toOffset;

        while (i < (32 + fromOffset + length)) {
            assembly {
                let tmp := mload(add(from, i))
                mstore(add(to, j), tmp)
            }
            i += 32;
            j += 32;
        }

        return to;
    }

    // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
    // Duplicate Solidity's ecrecover, but catching the CALL return value
    function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
        // We do our own memory management here. Solidity uses memory offset
        // 0x40 to store the current end of memory. We write past it (as
        // writes are memory extensions), but don't update the offset so
        // Solidity will reuse it. The memory used here is only needed for
        // this context.

        // FIXME: inline assembly can't access return values
        bool ret;
        address addr;

        assembly {
            let size := mload(0x40)
            mstore(size, hash)
            mstore(add(size, 32), v)
            mstore(add(size, 64), r)
            mstore(add(size, 96), s)

            // NOTE: we can reuse the request memory because we deal with
            //       the return code
            ret := call(3000, 1, 0, size, 128, size, 32)
            addr := mload(size)
        }

        return (ret, addr);
    }

    // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
    function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
        bytes32 r;
        bytes32 s;
        uint8 v;

        if (sig.length != 65)
          return (false, 0);

        // The signature format is a compact form of:
        //   {bytes32 r}{bytes32 s}{uint8 v}
        // Compact means, uint8 is not padded to 32 bytes.
        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))

            // Here we are loading the last 32 bytes. We exploit the fact that
            // 'mload' will pad with zeroes if we overread.
            // There is no 'mload8' to do this, but that would be nicer.
            v := byte(0, mload(add(sig, 96)))

            // Alternative solution:
            // 'byte' is not working due to the Solidity parser, so lets
            // use the second best option, 'and'
            // v := and(mload(add(sig, 65)), 255)
        }

        // albeit non-transactional signatures are not specified by the YP, one would expect it
        // to match the YP range of [27, 28]
        //
        // geth uses [0, 1] and some clients have followed. This might change, see:
        //  https://github.com/ethereum/go-ethereum/issues/2053
        if (v < 27)
          v += 27;

        if (v != 27 && v != 28)
            return (false, 0);

        return safer_ecrecover(hash, v, r, s);
    }

    function safeMemoryCleaner() internal pure {
        assembly {
            let fmem := mload(0x40)
            codecopy(fmem, codesize, sub(msize, fmem))
        }
    }

}
// </ORACLIZE_API>

//pragma solidity ^0.4.0;
//import "./oraclizeAPI.sol";
contract ExampleContract is usingOraclize {

   string public ETHUSD;
   address public mySender;
   address public myCbAddress;
   uint public myUrlPrice;
   uint public myBalance;
   string public mylog1;
   string public mylog2;
   event LogConstructorInitiated(string nextStep);
   event LogPriceUpdated(string price);
   event LogNewOraclizeQuery(string description);

   function ExampleContract() payable {
//       OAR = OraclizeAddrResolverI(0x904a3eB991FA099D31B1F160006C01460c2D1dD8);
//       OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
       emit LogConstructorInitiated("Constructor was initiated. Call 'updatePrice()' to send the Oraclize Query.");
   }

    // 实现可以往智能合约转入余额
    function () payable{

    }

   function __callback(bytes32 myid, string result) {
       mySender = msg.sender;
       myCbAddress = oraclize_cbAddress();
       if (msg.sender != oraclize_cbAddress()) revert();
       ETHUSD = result;
       LogPriceUpdated(result);
   }

    function getUrlPrice() returns (uint price){
        return oraclize_getPrice("URL");
    }

    function getcbAddress() returns (address tmp) {
        return oraclize_cbAddress();
    }

    function getBalance() returns (uint balance){
        return this.balance;
    }

    function getUrlPrice2() public view returns (uint price){
        return oraclize_getPrice("URL");
    }

    function getcbAddress2() public view returns (address tmp) {
        return oraclize_cbAddress();
    }

    function getBalance2() public view returns (uint balance){
        return this.balance;
    }

    function getORIAddress()public view returns (address tmp){
        return OAR.getAddress();
    }

    function getCodeSize2(address _addr) public view returns(uint _size) {
        assembly {
            _size := extcodesize(_addr)
        }
    }

    function oraclize_getPrice2(string datasource) oraclizeAPI public view returns (uint){
        return oraclize.getPrice(datasource);
    }

    function updatePrice2() payable {
        oraclize_query("URL", "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price");
    }

    // examplecontract.updatePrice({from: eth.accounts[0], value: 200000000000000000, gas:200000})
   function updatePrice() payable {
       myUrlPrice = oraclize_getPrice("URL");
       myBalance = this.balance;
       emit LogNewOraclizeQuery("LYH========= update price.");
       if (oraclize_getPrice("URL") > this.balance) {
           emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
       } else {
           emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
           oraclize_query("URL", "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price");
       }
   }

    //examplecontract.updateBtc({from: eth.accounts[0], value: 200000000000000000, gas:200000})
    function updateBtc() payable {
       myUrlPrice = oraclize_getPrice("URL");
       myBalance = this.balance;
       emit LogNewOraclizeQuery("LYH========= update price.");
       if (oraclize_getPrice("URL") > this.balance) {
           emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
       } else {
           emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
           oraclize_query("URL", "json(https://www.bitalong.com/api/index/ticker/btc_usdt).last");
       }
   }
}

3, 合约web3deploy代码(使用solc 0.4.25版本)

var examplecontractContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"getBalance2","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"myUrlPrice","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"getBalance","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"getUrlPrice","outputs":[{"name":"price","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"mylog2","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"myid","type":"bytes32"},{"name":"result","type":"string"}],"name":"__callback","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"getcbAddress","outputs":[{"name":"tmp","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"updatePrice2","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[{"name":"myid","type":"bytes32"},{"name":"result","type":"string"},{"name":"proof","type":"bytes"}],"name":"__callback","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getUrlPrice2","outputs":[{"name":"price","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getcbAddress2","outputs":[{"name":"tmp","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getORIAddress","outputs":[{"name":"tmp","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"getCodeSize2","outputs":[{"name":"_size","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"updatePrice","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"ETHUSD","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"myCbAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"updateBtc","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"myBalance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"datasource","type":"string"}],"name":"oraclize_getPrice2","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"mySender","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"mylog1","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":true,"stateMutability":"payable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"nextStep","type":"string"}],"name":"LogConstructorInitiated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"price","type":"string"}],"name":"LogPriceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"description","type":"string"}],"name":"LogNewOraclizeQuery","type":"event"}]);
var examplecontract = examplecontractContract.new(
   {
     from: web3.eth.accounts[0], 
     data: '0x60806040527f11a3fca63f87bd67d7f9f72b744acc8be2193705e7a734ac3a773d35d259e87b60405180806020018281038252604b8152602001807f436f6e7374727563746f722077617320696e697469617465642e2043616c6c2081526020017f27757064617465507269636528292720746f2073656e6420746865204f72616381526020017f6c697a652051756572792e00000000000000000000000000000000000000000081525060600191505060405180910390a1612a06806100c76000396000f30060806040526004361061011d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630a70cae01461011f578063117e9f4e1461014a57806312065fe01461017557806321effa2e146101a057806325a027d4146101cb57806327dc297e1461025b578063317648e5146102d2578063352e6dec1461032957806338bbfa50146103335780633d9c4117146103f05780635412778f1461041b57806359f22de41461047257806363c74942146104c9578063673a7e281461052057806373db08441461052a57806379e1e934146105ba578063ac7e520614610611578063c9116b691461061b578063ce7d04ab14610646578063f55a4bc1146106c3578063f8c5079e1461071a575b005b34801561012b57600080fd5b506101346107aa565b6040518082815260200191505060405180910390f35b34801561015657600080fd5b5061015f6107c9565b6040518082815260200191505060405180910390f35b34801561018157600080fd5b5061018a6107cf565b6040518082815260200191505060405180910390f35b3480156101ac57600080fd5b506101b56107ee565b6040518082815260200191505060405180910390f35b3480156101d757600080fd5b506101e0610833565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610220578082015181840152602081019050610205565b50505050905090810190601f16801561024d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561026757600080fd5b506102d06004803603810190808035600019169060200190929190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091929192905050506108d1565b005b3480156102de57600080fd5b506102e7610a52565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610331610a61565b005b34801561033f57600080fd5b506103ee6004803603810190808035600019169060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610aff565b005b3480156103fc57600080fd5b50610405610b04565b6040518082815260200191505060405180910390f35b34801561042757600080fd5b50610430610b49565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561047e57600080fd5b50610487610b58565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156104d557600080fd5b5061050a600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610c1f565b6040518082815260200191505060405180910390f35b610528610c2a565b005b34801561053657600080fd5b5061053f610f36565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561057f578082015181840152602081019050610564565b50505050905090810190601f1680156105ac5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156105c657600080fd5b506105cf610fd4565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610619610ffa565b005b34801561062757600080fd5b50610630611306565b6040518082815260200191505060405180910390f35b34801561065257600080fd5b506106ad600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929050505061130c565b6040518082815260200191505060405180910390f35b3480156106cf57600080fd5b506106d86116dc565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561072657600080fd5b5061072f611702565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561076f578082015181840152602081019050610754565b50505050905090810190601f16801561079c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60003073ffffffffffffffffffffffffffffffffffffffff1631905090565b60085481565b60003073ffffffffffffffffffffffffffffffffffffffff1631905090565b600061082e6040805190810160405280600381526020017f55524c00000000000000000000000000000000000000000000000000000000008152506117a0565b905090565b600b8054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108c95780601f1061089e576101008083540402835291602001916108c9565b820191906000526020600020905b8154815290600101906020018083116108ac57829003601f168201915b505050505081565b33600660006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061091a611b70565b600760006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610962611b70565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561099b57600080fd5b80600590805190602001906109b1929190612935565b507f71f1a5645e51a2da828ffcf79cc17da88eb25e1bca8b9dced23210847a4769c1816040518080602001828103825283818151815260200191508051906020019080838360005b83811015610a145780820151818401526020810190506109f9565b50505050905090810190601f168015610a415780820380516001836020036101000a031916815260200191505b509250505060405180910390a15050565b6000610a5c611b70565b905090565b610afc6040805190810160405280600381526020017f55524c0000000000000000000000000000000000000000000000000000000000815250606060405190810160405280604081526020017f6a736f6e2868747470733a2f2f6170692e70726f2e636f696e626173652e636f81526020017f6d2f70726f64756374732f4554482d5553442f7469636b6572292e7072696365815250611ece565b50565b505050565b6000610b446040805190810160405280600381526020017f55524c00000000000000000000000000000000000000000000000000000000008152506117a0565b905090565b6000610b53611b70565b905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015610bdf57600080fd5b505af1158015610bf3573d6000803e3d6000fd5b505050506040513d6020811015610c0957600080fd5b8101908080519060200190929190505050905090565b6000813b9050919050565b610c686040805190810160405280600381526020017f55524c00000000000000000000000000000000000000000000000000000000008152506117a0565b6008819055503073ffffffffffffffffffffffffffffffffffffffff16316009819055507f621c2856e3b87f81235f8ac8a22bbb40a0142961960710d00b2b6c380902b57e60405180806020018281038252601a8152602001807f4c59483d3d3d3d3d3d3d3d3d207570646174652070726963652e00000000000081525060200191505060405180910390a13073ffffffffffffffffffffffffffffffffffffffff1631610d4a6040805190810160405280600381526020017f55524c00000000000000000000000000000000000000000000000000000000008152506117a0565b1115610e09577f621c2856e3b87f81235f8ac8a22bbb40a0142961960710d00b2b6c380902b57e60405180806020018281038252604b8152602001807f4f7261636c697a6520717565727920776173204e4f542073656e742c20706c6581526020017f6173652061646420736f6d652045544820746f20636f76657220666f7220746881526020017f652071756572792066656500000000000000000000000000000000000000000081525060600191505060405180910390a1610f34565b7f621c2856e3b87f81235f8ac8a22bbb40a0142961960710d00b2b6c380902b57e6040518080602001828103825260358152602001807f4f7261636c697a65207175657279207761732073656e742c207374616e64696e81526020017f6720627920666f722074686520616e737765722e2e000000000000000000000081525060400191505060405180910390a1610f326040805190810160405280600381526020017f55524c0000000000000000000000000000000000000000000000000000000000815250606060405190810160405280604081526020017f6a736f6e2868747470733a2f2f6170692e70726f2e636f696e626173652e636f81526020017f6d2f70726f64756374732f4554482d5553442f7469636b6572292e7072696365815250611ece565b505b565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610fcc5780601f10610fa157610100808354040283529160200191610fcc565b820191906000526020600020905b815481529060010190602001808311610faf57829003601f168201915b505050505081565b600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6110386040805190810160405280600381526020017f55524c00000000000000000000000000000000000000000000000000000000008152506117a0565b6008819055503073ffffffffffffffffffffffffffffffffffffffff16316009819055507f621c2856e3b87f81235f8ac8a22bbb40a0142961960710d00b2b6c380902b57e60405180806020018281038252601a8152602001807f4c59483d3d3d3d3d3d3d3d3d207570646174652070726963652e00000000000081525060200191505060405180910390a13073ffffffffffffffffffffffffffffffffffffffff163161111a6040805190810160405280600381526020017f55524c00000000000000000000000000000000000000000000000000000000008152506117a0565b11156111d9577f621c2856e3b87f81235f8ac8a22bbb40a0142961960710d00b2b6c380902b57e60405180806020018281038252604b8152602001807f4f7261636c697a6520717565727920776173204e4f542073656e742c20706c6581526020017f6173652061646420736f6d652045544820746f20636f76657220666f7220746881526020017f652071756572792066656500000000000000000000000000000000000000000081525060600191505060405180910390a1611304565b7f621c2856e3b87f81235f8ac8a22bbb40a0142961960710d00b2b6c380902b57e6040518080602001828103825260358152602001807f4f7261636c697a65207175657279207761732073656e742c207374616e64696e81526020017f6720627920666f722074686520616e737765722e2e000000000000000000000081525060400191505060405180910390a16113026040805190810160405280600381526020017f55524c0000000000000000000000000000000000000000000000000000000000815250606060405190810160405280603d81526020017f6a736f6e2868747470733a2f2f7777772e626974616c6f6e672e636f6d2f617081526020017f692f696e6465782f7469636b65722f6274635f75736474292e6c617374000000815250611ece565b505b565b60095481565b6000806000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16148061137c5750600061137a6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612470565b145b1561138d5761138b600061247b565b505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561141257600080fd5b505af1158015611426573d6000803e3d6000fd5b505050506040513d602081101561143c57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415156115a4576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15801561152857600080fd5b505af115801561153c573d6000803e3d6000fd5b505050506040513d602081101561155257600080fd5b8101908080519060200190929190505050600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663524f3889836040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561164e578082015181840152602081019050611633565b50505050905090810190601f16801561167b5780820380516001836020036101000a031916815260200191505b5092505050602060405180830381600087803b15801561169a57600080fd5b505af11580156116ae573d6000803e3d6000fd5b505050506040513d60208110156116c457600080fd5b81019080805190602001909291905050509050919050565b600660009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600a8054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156117985780601f1061176d57610100808354040283529160200191611798565b820191906000526020600020905b81548152906001019060200180831161177b57829003601f168201915b505050505081565b6000806000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614806118105750600061180e6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612470565b145b156118215761181f600061247b565b505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1580156118a657600080fd5b505af11580156118ba573d6000803e3d6000fd5b505050506040513d60208110156118d057600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515611a38576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1580156119bc57600080fd5b505af11580156119d0573d6000803e3d6000fd5b505050506040513d60208110156119e657600080fd5b8101908080519060200190929190505050600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663524f3889836040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611ae2578082015181840152602081019050611ac7565b50505050905090810190601f168015611b0f5780820380516001836020036101000a031916815260200191505b5092505050602060405180830381600087803b158015611b2e57600080fd5b505af1158015611b42573d6000803e3d6000fd5b505050506040513d6020811015611b5857600080fd5b81019080805190602001909291905050509050919050565b6000806000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161480611be057506000611bde6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612470565b145b15611bf157611bef600061247b565b505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611c7657600080fd5b505af1158015611c8a573d6000803e3d6000fd5b505050506040513d6020811015611ca057600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515611e08576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611d8c57600080fd5b505af1158015611da0573d6000803e3d6000fd5b505050506040513d6020811015611db657600080fd5b8101908080519060200190929190505050600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c281d19e6040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611e8e57600080fd5b505af1158015611ea2573d6000803e3d6000fd5b505050506040513d6020811015611eb857600080fd5b8101908080519060200190929190505050905090565b60008060008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161480611f4057506000611f3e6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16612470565b145b15611f5157611f4f600061247b565b505b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b158015611fd657600080fd5b505af1158015611fea573d6000803e3d6000fd5b505050506040513d602081101561200057600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515612168576000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338cc48316040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1580156120ec57600080fd5b505af1158015612100573d6000803e3d6000fd5b505050506040513d602081101561211657600080fd5b8101908080519060200190929190505050600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663524f3889856040518263ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018080602001828103825283818151815260200191508051906020019080838360005b838110156122125780820151818401526020810190506121f7565b50505050905090810190601f16801561223f5780820380516001836020036101000a031916815260200191505b5092505050602060405180830381600087803b15801561225e57600080fd5b505af1158015612272573d6000803e3d6000fd5b505050506040513d602081101561228857600080fd5b8101908080519060200190929190505050905062030d403a02670de0b6b3a7640000018111156122be5760006001029150612469565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663adf59f9982600087876040518563ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808481526020018060200180602001838103835285818151815260200191508051906020019080838360005b8381101561237657808201518184015260208101905061235b565b50505050905090810190601f1680156123a35780820380516001836020036101000a031916815260200191505b50838103825284818151815260200191508051906020019080838360005b838110156123dc5780820151818401526020810190506123c1565b50505050905090810190601f1680156124095780820380516001836020036101000a031916815260200191505b50955050505050506020604051808303818588803b15801561242a57600080fd5b505af115801561243e573d6000803e3d6000fd5b50505050506040513d602081101561245557600080fd5b810190808051906020019092919050505091505b5092915050565b6000813b9050919050565b600061248561248c565b9050919050565b6000806124ac731d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed612470565b111561254d57731d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed6000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506125446040805190810160405280600b81526020017f6574685f6d61696e6e657400000000000000000000000000000000000000000081525061291b565b60019050612918565b600061256c73c03a2615d5efaf5f49f60b7bb6583eaec212fdf1612470565b111561260d5773c03a2615d5efaf5f49f60b7bb6583eaec212fdf16000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506126046040805190810160405280600c81526020017f6574685f726f707374656e33000000000000000000000000000000000000000081525061291b565b60019050612918565b600061262c73b7a07bcf2ba2f2703b24c0691b5278999c59ac7e612470565b11156126cd5773b7a07bcf2ba2f2703b24c0691b5278999c59ac7e6000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506126c46040805190810160405280600981526020017f6574685f6b6f76616e000000000000000000000000000000000000000000000081525061291b565b60019050612918565b60006126ec73146500cfd35b22e4a392fe0adc06de1a1368ed48612470565b111561278d5773146500cfd35b22e4a392fe0adc06de1a1368ed486000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506127846040805190810160405280600b81526020017f6574685f72696e6b65627900000000000000000000000000000000000000000081525061291b565b60019050612918565b60006127ac736f485c8bf6fc43ea212e93bbf8ce046c7f1cb475612470565b111561280f57736f485c8bf6fc43ea212e93bbf8ce046c7f1cb4756000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060019050612918565b600061282e7320e12a1f859b3feae5fb2a0a32c18f5a65555bbf612470565b1115612891577320e12a1f859b3feae5fb2a0a32c18f5a65555bbf6000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060019050612918565b60006128b07351efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa612470565b1115612913577351efaf4c8b3c9afbd5ab9f4bbc82784ab6ef8faa6000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060019050612918565b600090505b90565b8060029080519060200190612931929190612935565b5050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061297657805160ff19168380011785556129a4565b828001600101855582156129a4579182015b828111156129a3578251825591602001919060010190612988565b5b5090506129b191906129b5565b5090565b6129d791905b808211156129d35760008160009055506001016129bb565b5090565b905600a165627a7a72305820f83c8bbeeaaace7970e4983891d4190b866d041b836c0fe82ccfe183ad379bea0029', 
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

4, 挖矿并部署
miner.start(1); admin.sleepBlocks(1); miner.stop()

5, 此时会返回一个合约地址
Contract mined! address: 0x911c8db375034b1b4b313e8714d467348d97a29b transactionHash: 0x36dc8c0bd06d0b0774cc8cbd2f6f66bd0b7b796fa452910f0db1e9111df5c31c

6, 更新价格
examplecontract.updatePrice({from: eth.accounts[0], value: 100000000000000000})

//上面调用没有指定gas调用,否则会出现 "out of gas" 的情况,防止out of gas可以指定调用的gas
# 在执行指定的 SSTORE 出现 "out of gas"
DEBUG[11-27|02:05:46.668|core/vm/interpreter.go:256]             cost                   err=20000
DEBUG[11-27|02:05:46.668|core/vm/interpreter.go:257]             contract.Gas           err=13620
# 需要20000 当时contract 中只有 13620 

examplecontract.updatePrice({from: eth.accounts[0], value: 200000000000000000, gas:200000})
> examplecontract.updatePrice({from: eth.accounts[0], value: 200000000000000000, gas:200000})
"0xfe5f24f559171d36fb00b8105f973a54d18c2b1282ba1b25c008fea6f99604e2"
> miner.start(1); admin.sleepBlocks(1); miner.stop() 
null
> miner.start(1); admin.sleepBlocks(1); miner.stop()
null
> examplecontract.ETHUSD()
""
> examplecontract.ETHUSD()
""
> miner.start(1); admin.sleepBlocks(1); miner.stop()
null
> examplecontract.ETHUSD()
"105.68000000"

7, 两次挖矿解读
由于oraclize中刷新ETHUSD 是异步调用,导致第一次挖矿只是实现了转账的功能,
   第二次挖矿,oraclize异步调用,将数据回填到callback方法中的 ETHUSD。

四、在ethereum-bridge中,可以看到有数据调用
以下为打印的输出

# ethereum-bridge -H localhost:8545 -a 1 
Please wait...
[2018-11-27T06:59:07.211Z] INFO you are running ethereum-bridge - version: 0.6.1
[2018-11-27T06:59:07.214Z] INFO saving logs to: ./bridge.log
[2018-11-27T06:59:07.215Z] INFO using active mode
[2018-11-27T06:59:07.216Z] INFO Connecting to eth node http://localhost:8545
[2018-11-27T06:59:11.576Z] INFO connected to node type Geth/TestNode/v1.8.19-unstable-d136e985/linux-amd64/go1.10.3
[2018-11-27T06:59:14.769Z] WARN Using 0x20b91c6536492ade87503de51a5b7edad31149a8 to query contracts on your blockchain, make sure it is unlocked and do not use the same address to deploy your contracts
[2018-11-27T06:59:15.324Z] INFO deploying the oraclize connector contract...
[2018-11-27T07:00:03.045Z] INFO connector deployed to: 0xdc72cafa3ab6aa0931197611d66b47304a7082d0
[2018-11-27T07:00:03.515Z] INFO deploying the address resolver with a deterministic address...
[2018-11-27T07:01:04.824Z] INFO address resolver (OAR) deployed to: 0x6f485c8bf6fc43ea212e93bbf8ce046c7f1cb475
[2018-11-27T07:01:04.825Z] INFO updating connector pricing...
[2018-11-27T07:01:16.707Z] INFO successfully deployed all contracts
[2018-11-27T07:01:16.710Z] INFO instance configuration file saved to /usr/local/lib/node_modules/ethereum-bridge/config/instance/oracle_instance_20181127T020116.json
[2018-11-27T07:01:16.711Z] INFO you are using a deterministic OAR, you don't need to update your contract
[2018-11-27T07:01:17.516Z] INFO Listening @ 0xdc72cafa3ab6aa0931197611d66b47304a7082d0 (Oraclize Connector)

(Ctrl+C to exit)

[2018-11-27T07:16:30.662Z] INFO new Log1 event
{
    "parsed_log": {
        "contract_address": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24",
        "contract_myid": "0x4cd4e11699b7acea3b3cf5c5704ffb987420e016985ec987ab2f47d086b94f0f",
        "datasource": "URL",
        "formula": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
        "timestamp": 0,
        "gaslimit": 200000,
        "proofType": "0x00",
        "gasPrice": 0
    },
    "address": "0xdc72cafa3ab6aa0931197611d66b47304a7082d0",
    "blockNumber": 18,
    "transactionHash": "0x12f2528a4e6a3862dcb8bb76e3025bbb3a1d7f792b56a5aaa8d5220142e5cb13",
    "transactionIndex": 2,
    "blockHash": "0x0eb168a446cd16464282a4cbe433d66c52b736e9667fb8614221b662b98fefa6",
    "logIndex": 2,
    "removed": false,
    "event": "Log1",
    "args": {
        "sender": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24",
        "cid": "0x4cd4e11699b7acea3b3cf5c5704ffb987420e016985ec987ab2f47d086b94f0f",
        "timestamp": {
            "s": 1,
            "e": 0,
            "c": [
                0
            ]
        },
        "datasource": "URL",
        "arg": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
        "gaslimit": {
            "s": 1,
            "e": 5,
            "c": [
                200000
            ]
        },
        "proofType": "0x00",
        "gasPrice": {
            "s": 1,
            "e": 0,
            "c": [
                0
            ]
        }
    },
    "block_timestamp": 1543302987
}
[2018-11-27T07:16:31.153Z] INFO new Log1 event
{
    "parsed_log": {
        "contract_address": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24",
        "contract_myid": "0x705d063419c6342743c9f04fc75795e778ec34afca528a504a2003a697da7c8e",
        "datasource": "URL",
        "formula": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
        "timestamp": 0,
        "gaslimit": 200000,
        "proofType": "0x00",
        "gasPrice": 0
    },
    "address": "0xdc72cafa3ab6aa0931197611d66b47304a7082d0",
    "blockNumber": 18,
    "transactionHash": "0xfe5f24f559171d36fb00b8105f973a54d18c2b1282ba1b25c008fea6f99604e2",
    "transactionIndex": 3,
    "blockHash": "0x0eb168a446cd16464282a4cbe433d66c52b736e9667fb8614221b662b98fefa6",
    "logIndex": 5,
    "removed": false,
    "event": "Log1",
    "args": {
        "sender": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24",
        "cid": "0x705d063419c6342743c9f04fc75795e778ec34afca528a504a2003a697da7c8e",
        "timestamp": {
            "s": 1,
            "e": 0,
            "c": [
                0
            ]
        },
        "datasource": "URL",
        "arg": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
        "gaslimit": {
            "s": 1,
            "e": 5,
            "c": [
                200000
            ]
        },
        "proofType": "0x00",
        "gasPrice": {
            "s": 1,
            "e": 0,
            "c": [
                0
            ]
        }
    },
    "block_timestamp": 1543302987
}
[2018-11-27T07:16:32.940Z] INFO new HTTP query created, id: 03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073
[2018-11-27T07:16:32.962Z] INFO checking HTTP query 03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073 status in 0 seconds
[2018-11-27T07:16:32.964Z] INFO checking HTTP query 03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073 status every 5 seconds...
[2018-11-27T07:16:33.130Z] INFO new HTTP query created, id: f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b
[2018-11-27T07:16:33.134Z] INFO checking HTTP query f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b status in 0 seconds
[2018-11-27T07:16:33.135Z] INFO checking HTTP query f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b status every 5 seconds...
[2018-11-27T07:16:41.619Z] INFO 03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073 HTTP query result: 
{
    "result": {
        "_timestamp": 1543302992,
        "daterange": [
            1543302992,
            1543304792
        ],
        "interval": 3600,
        "id2": "705d063419c6342743c9f04fc75795e778ec34afca528a504a2003a697da7c8e",
        "actions": [],
        "id": "03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073",
        "version": 3,
        "_timestamp_creation": 1543302992,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1543302987,
            "type": "blockchain",
            "name": "eth_DD16B4DB79"
        },
        "active": true,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2018-11-27T07:16:45.140Z] INFO f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b HTTP query result: 
	{
    "result": {
        "_timestamp": 1543302992,
        "daterange": [
            1543302992,
            1543304792
        ],
        "interval": 3600,
        "id2": "4cd4e11699b7acea3b3cf5c5704ffb987420e016985ec987ab2f47d086b94f0f",
        "actions": [],
        "id": "f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b",
        "version": 3,
        "_timestamp_creation": 1543302992,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1543302987,
            "type": "blockchain",
            "name": "eth_DD16B4DB79"
        },
        "active": true,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2018-11-27T07:16:46.254Z] INFO 03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073 HTTP query result: 
	{
    "result": {
        "_timestamp": 1543303000,
        "id": "03a2a9598659633b3bd7cf919cb98cb6ca0d274ceb5235b3825eb4d21907b073",
        "daterange": [
            1543302992,
            1543304792
        ],
        "_lock": false,
        "id2": "705d063419c6342743c9f04fc75795e778ec34afca528a504a2003a697da7c8e",
        "actions": [],
        "interval": 3600,
        "checks": [
            {
                "errors": [],
                "success": true,
                "timestamp": 1543303000,
                "results": [
                    "105.68000000"
                ],
                "proofs": [
                    null
                ],
                "match": true
            }
        ],
        "version": 3,
        "_timestamp_creation": 1543302992,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1543302987,
            "type": "blockchain",
            "name": "eth_DD16B4DB79"
        },
        "active": false,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2018-11-27T07:16:46.272Z] INFO sending __callback tx...
	{
    "contract_myid": "0x705d063419c6342743c9f04fc75795e778ec34afca528a504a2003a697da7c8e",
    "contract_address": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24"
}
[2018-11-27T07:16:47.030Z] INFO f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b HTTP query result: 
	{
    "result": {
        "_timestamp": 1543303003,
        "id": "f978fe6316c57a89c6efb8b2ebf981365fa2084a68d180cb7c11324c9f18058b",
        "daterange": [
            1543302992,
            1543304792
        ],
        "_lock": false,
        "id2": "4cd4e11699b7acea3b3cf5c5704ffb987420e016985ec987ab2f47d086b94f0f",
        "actions": [],
        "interval": 3600,
        "checks": [
            {
                "errors": [],
                "success": true,
                "timestamp": 1543303003,
                "results": [
                    "105.68000000"
                ],
                "proofs": [
                    null
                ],
                "match": true
            }
        ],
        "version": 3,
        "_timestamp_creation": 1543302992,
        "context": {
            "protocol": "eth",
            "relative_timestamp": 1543302987,
            "type": "blockchain",
            "name": "eth_DD16B4DB79"
        },
        "active": false,
        "hidden": false,
        "payload": {
            "conditions": [
                {
                    "query": "json(https://api.pro.coinbase.com/products/ETH-USD/ticker).price",
                    "proof_type": 0,
                    "check_op": "tautology",
                    "datasource": "URL",
                    "value": null
                }
            ]
        }
    },
    "success": true
}
[2018-11-27T07:16:47.039Z] INFO sending __callback tx...
	{
    "contract_myid": "0x4cd4e11699b7acea3b3cf5c5704ffb987420e016985ec987ab2f47d086b94f0f",
    "contract_address": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24"
}
[2018-11-27T07:17:58.280Z] INFO contract 0xb8040821356bc3c84ddbe947a6004a4dc74bfa24 __callback tx sent, transaction hash: 0x3363f29ee643a931f1d614ddc9c97f8742d0a8984dc280b1062338da75cf38eb
	{
    "myid": "0x705d063419c6342743c9f04fc75795e778ec34afca528a504a2003a697da7c8e",
    "result": "105.68000000",
    "proof": null,
    "proof_type": "0x00",
    "contract_address": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24",
    "gas_limit": 200000,
    "gas_price": null
}


[2018-11-27T07:17:58.756Z] INFO contract 0xb8040821356bc3c84ddbe947a6004a4dc74bfa24 __callback tx sent, transaction hash: 0x7628eebcb1b38c8b9f1662a7b61f5f071b6bfb09e08747c2032edc3eb89a61c2
	{
    "myid": "0x4cd4e11699b7acea3b3cf5c5704ffb987420e016985ec987ab2f47d086b94f0f",
    "result": "105.68000000",
    "proof": null,
    "proof_type": "0x00",
    "contract_address": "0xb8040821356bc3c84ddbe947a6004a4dc74bfa24",
    "gas_limit": 200000,
    "gas_price": null
}

[2018-11-27T07:18:45.125Z] INFO transaction hash 0x3363f29ee643a931f1d614ddc9c97f8742d0a8984dc280b1062338da75cf38eb was confirmed in block 0x0955c1985be0750021de9edbbb5155e867ec8f9333cb8f66aa7ab0fb9fc67582
[2018-11-27T07:18:45.597Z] INFO transaction hash 0x7628eebcb1b38c8b9f1662a7b61f5f071b6bfb09e08747c2032edc3eb89a61c2 was confirmed in block 0x0955c1985be0750021de9edbbb5155e867ec8f9333cb8f66aa7ab0fb9fc67582

参考资料:
官网:http://docs.oraclize.it/#home
讨论网页:https://gitter.im/oraclize/ethereum-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
oraclize github地址:https://github.com/oraclize/ethereum-api
ethereum-bridge地址:https://github.com/oraclize/ethereum-bridge/
 

<think>好的,我现在需要帮助用户了解区块链钱包客户端的代码实现,特别是用户提到的九个功能模块。首先,我需要回顾之前给出的回答,确保这次的内容更详细,覆盖所有新提到的模块,比如身份管理、DApp集成、DeFi聚合器、NFT资产管理和跨链互操作。 用户可能是一位开发者,或者是对区块链技术有深入兴趣的技术人员,想要构建一个功能全面的钱包客户端。他们可能希望了解每个模块的具体实现细节、技术选型以及安全方面的考虑。需要确保回答结构清晰,分模块说明,同时提供代码示例和技术建议。 首先,身份管理模块,除了之前的密钥管理,可能还涉及去中心化身份(DID),比如使用W3C的DID标准,可能需要集成不同的身份协议,如ERC725或OAuth。需要考虑如何生成DID文档,以及如何管理凭证。 钱包管理模块需要扩展多链支持,比如支持BTC、ETH以及其他链的钱包,可能需要用到分层确定性钱包(HD Wallet),遵循BIP44标准。同时,冷热钱包分离的实现,可能需要设计不同的存储和安全策略。 资产管理模块需要处理不同资产的显示和估值,可能需要与多个区块链节点交互,获取余额和交易记录。Token检测需要动态识别,比如ERC20合约的自动发现。 交易功能模块除了基本的交易构造,还需要支持智能合约交互,比如在以太坊调用合约方法。Gas费预估和交易加速机制也是需要考虑的,可能需要集成第三方API如Gas Station Network。 安全中心需要更详细的多因素认证方法,比如时间基一次性密码(TOTP)、生物识别等。风险监控可能涉及交易模式分析和地址黑名单检查,需要实时更新威胁情报。 DApp集成模块需要实现Web3提供者,注入到DApp浏览器中,处理RPC请求。沙箱环境隔离是关键,可能需要使用iframe或Web Worker来确保安全,防止恶意脚本访问敏感数据。 DeFi聚合器需要聚合不同协议的流动性,比如Uniswap、Compound,可能需要调用它们的智能合约或API。收益计算器需要考虑APY、手续费等因素,可能需要链下计算或索引数据。 NFT资产管理要支持不同标准的代币,如ERC721和ERC1155,需要解析元数据,可能涉及IPFS或Arweave的集成。展示部分可能需要使用WebGL或Canvas来渲染3D模型。 跨链互操作需要处理跨链桥和原子交换,可能涉及哈希时间锁定合约(HTLC)或使用中继链技术。需要处理不同链的交易格式和确认时间,确保原子性。 在技术选型方面,前端可能需要React或Flutter,核心层用Rust或Go,安全库使用audited的版本。需要引用更多的开源项目作为参考,比如MetaMask、Rainbow Wallet等。 同时,要确保每个模块都有代码示例,比如DID的生成、HD钱包的实现、Gas预估的代码片段,这样用户能更直观地理解实现方式。安全方面要强调私钥管理、内存加密、审计日志的重要性。 最后,总结部分需要提醒用户注意合规性、测试网实践和持续的安全更新。可能用户在实际开发中会遇到性能问题,比如跨链交易延迟,或者DApp沙箱的安全漏洞,需要给出解决方案,比如使用状态通道优化或定期安全审计。 需要确保回答覆盖所有用户提到的模块,结构清晰,技术细节准确,同时保持语言简洁易懂。可能还需要检查是否有遗漏的功能点,比如通知中心或用户反馈模块,但根据用户的问题,主要集中在列出的九个模块。确认每个子模块都有对应的实现要点和技术建议,帮助用户全面了解开发流程。</think>以下是区块链钱包客户端的完整功能模块实现方案(含技术实现细节与代码示例): --- ### 一、身份管理模块 **技术实现:** 1. **DID身份体系** ```python # ERC-725身份合约交互示例 from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io')) def create_did_identity(): private_key = os.urandom(32) did = "did:eth:" + w3.eth.account.from_key(private_key).address return { "did": did, "private_key": private_key.hex() } ``` 2. **身份凭证管理** - 支持W3C VC标准数据格式 - 集成zk-SNARKs实现选择性披露 - 生物特征加密存储(iOS Secure Enclave/Android Titan M) --- ### 二、钱包管理模块 **核心功能:** 1. **多链钱包体系** ```javascript // BIP44路径生成示例(BTC/ETH) const derivePath = (chainType, index) => { const paths = { 'BTC': "m/44'/0'/0'/0", 'ETH': "m/44'/60'/0'/0" } return `${paths[chainType]}/${index}`; } ``` 2. **冷热钱包架构** - 热钱包:内存加密存储,限额自动归集 - 冷钱包:离线签名(二维码/U盾通信) - 硬件钱包集成(Ledger/Trezor HID协议) --- ### 三、资产管理模块 **关键技术:** 1. **资产聚合引擎** ```go // 多链余额查询(并发实现) func QueryBalances(address string, chains []Chain) map[Chain]float64 { var wg sync.WaitGroup balances := make(map[Chain]float64) for _, chain := range chains { wg.Add(1) go func(c Chain) { defer wg.Done() balances[c] = c.RPC.GetBalance(address) }(chain) } wg.Wait() return balances } ``` 2. **自动Token检测** - 通过EIP-165检测合约类型 - 动态加载ERC-20/ERC-721元数据 --- ### 四、交易功能模块 **核心实现:** 1. **智能合约交互层** ```solidity // 交易中继抽象合约 abstract contract Relay { function metaCall( address target, bytes calldata data, uint256 fee ) external payable virtual returns (bytes memory); } ``` 2. **Gas优化机制** - EIP-1559费用市场支持 - 交易批处理(Multicall) - 内存池监控与加速替换(RBF/CFR) --- ### 五、安全中心模块 **防护体系:** ```java // Android密钥库集成示例 public class SecureKeyStore { private KeyStore keyStore; public void saveKey(String alias, PrivateKey key) { KeyProtection protection = new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) .build(); keyStore.setEntry(alias, new KeyStore.SecretKeyEntry(key), protection); } } ``` **安全策略:** - 交易行为画像分析(机器学习模型) - 钓鱼地址实时拦截(Bloom过滤器) - 硬件级安全模块(HSM)集成 --- ### 六、DApp集成模块 **实现方案:** 1. **Web3 Provider注入** ```javascript // 钱包注入DApp的Web3对象 window.ethereum = { request: ({ method, params }) => { switch(method) { case 'eth_sendTransaction': return wallet.signAndSendTx(params[0]); case 'personal_sign': return wallet.signMessage(params[0]); } } } ``` 2. **沙箱安全隔离** - WASM执行环境 - 权限控制系统(白名单API访问) - 交易模拟预执行(EIP-3074) --- ### 七、DeFi聚合器 **核心逻辑:** ```python # 最优利率计算(以借贷为例) def find_best_rate(protocols, amount, duration): rates = [] for protocol in protocols: apy = protocol.calculate_apy(amount, duration) fee = protocol.get_processing_fee() rates.append({ 'protocol': protocol.name, 'net_apy': apy - fee }) return sorted(rates, key=lambda x: x['net_apy'], reverse=True)[0] ``` **聚合策略:** - 跨协议闪电贷组合 - 滑点优化算法(DEX聚合) - 风险对冲策略引擎 --- ### 八、NFT资产管理 **关键技术点:** 1. **跨链NFT桥接** ```solidity // ERC-721跨链封装合约(简化版) contract NFTBridge { function lockNFT(address nftContract, uint256 tokenId) external { IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId); emit Locked(block.chainid, nftContract, tokenId); } function mintWrappedNFT(uint256 originChainId, address originContract, uint256 tokenId) external { _mint(msg.sender, tokenId); } } ``` 2. **NFT元数据解析** - IPFS CID解码(多网关fallback) - 链下元数据验证(EIP-3668) - 3D模型渲染引擎(WebGL/WebGPU) --- ### 九、跨链互操作模块 **实现方案:** 1. **原子交换协议** ```rust // 哈希时间锁合约实现(Rust示例) #[ink(message)] pub fn initiate_swap( &mut self, hashlock: [u8; 32], timelock: Timestamp, value: Balance ) -> Result<()> { self.swaps.insert(hashlock, Swap { sender: self.env().caller(), value, timelock, state: SwapState::Initiated }); Ok(()) } ``` 2. **跨链消息传递** - IBC协议适配器 - 轻客户端验证(Merkle Proof) - 中继网络激励机制 --- ### 技术架构建议 **分层设计:** ``` ┌───────────────────────┐ │ 用户界面层 │ React/Flutter ├───────────────────────┤ │ 业务逻辑层 │ Rust + WASM ├───────────────────────┤ │ 协议适配层 │ libp2p + gRPC ├───────────────────────┤ │ 安全加密层 │ Ring Crypto + SE └───────────────────────┘ ``` **关键依赖库:** - 密码学:libsecp256k1, sodiumoxide - 区块链交互:ethers-rs, bitcoinj - 安全存储:SQLCipher, Realm --- ### 开发注意事项 1. **合规性实现:** - 集成Chainalysis API进行交易监控 - 支持TRM Labs的地址筛查 - 实现旅行规则(Travel Rule)协议 2. **性能优化:** - 状态树剪枝(UTXO集合压缩) - 交易缓存池分级处理 - 异步IO事件驱动架构 3. **测试策略:** - 模糊测试(libFuzzer) - 形式化验证(Certora Prover) - 主网分阶段灰度发布 建议从模块化架构入手,优先实现核心的密钥管理和交易引擎,逐步扩展DeFi与跨链功能。所有敏感操作必须通过安全审计,推荐使用CertiK或Trail of Bits等专业审计机构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值