Solidity 學(xué)習(xí)筆記(1)- string和bytes

固定長度的bytes轉(zhuǎn)化為string

如果是固定大小字節(jié)數(shù)組轉(zhuǎn)string,那么就需要先將字節(jié)數(shù)組轉(zhuǎn)動(dòng)態(tài)字節(jié)數(shù)組,再轉(zhuǎn)字符串。

pragma solidity ^0.4.4;

contract C {

   function byte32ToString(bytes32 b) constant returns (string) {
       
       bytes memory names = new bytes(b.length);
       
       for(uint i = 0; i < b.length; i++) {
           
           names[i] = b[i];
       }
       
       return string(names);
   }
   

但是,如果字符串不是占滿32個(gè)字節(jié)。那么后面就會(huì)由\u0000進(jìn)行填充。所以我們需要將這些空字符去掉。
改進(jìn)的方法:

pragma solidity ^0.4.4;

contract C {
    
    function bytes32ToString(bytes32 x) constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

    function bytes32ArrayToString(bytes32[] data) constant returns (string) {
        bytes memory bytesString = new bytes(data.length * 32);
        uint urlLength;
        for (uint i = 0; i< data.length; i++) {
            for (uint j = 0; j < 32; j++) {
                byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j)));
                if (char != 0) {
                    bytesString[urlLength] = char;
                    urlLength += 1;
                }
            }
        }
        bytes memory bytesStringTrimmed = new bytes(urlLength);
        for (i = 0; i < urlLength; i++) {
            bytesStringTrimmed[i] = bytesString[i];
        }
        return string(bytesStringTrimmed);
    }    
}

其中在進(jìn)行char的轉(zhuǎn)換時(shí)使用了一個(gè)算法。這里針對(duì)單字符轉(zhuǎn)化給一個(gè)更清晰的例子:

pragma solidity ^0.4.4;

contract C {
    
    // 0x6c
    
    function uintValue() constant returns (uint) {
        
        return uint(0x6c);
    }
    
    function bytes32To0x6c() constant returns (bytes32) {
        
        return bytes32(0x6c);
    }
    
    function bytes32To0x6cLeft00() constant returns (bytes32) {
        
        return bytes32(uint(0x6c) * 2 ** (8 * 0));
    }
    
    function bytes32To0x6cLeft01() constant returns (bytes32) {
        
        return bytes32(uint(0x6c) * 2 ** (8 * 1));
    }
    
    function bytes32To0x6cLeft31() constant returns (bytes32) {
        
        return bytes32(uint(0x6c) * 2 ** (8 * 31));
    }
}

我們可以看到:
bytes32(uint(0x6c) * 2 ** (8 * 31))就是將6c左移31位;
bytes32(uint(0x6c) * 2 ** (8 * 1))就是將6c左移1位;

所以,通過byte(bytes32(uint(x) * 2 ** (8 * j)))獲取到的始終是第0個(gè)字節(jié)。

image.png

最后在說明一點(diǎn):
string本身是一個(gè)特殊的動(dòng)態(tài)字節(jié)數(shù)組,所以它只能和bytes之間進(jìn)行轉(zhuǎn)換,不能和固定大小字節(jié)數(shù)組進(jìn)行直接轉(zhuǎn)換,如果是固定字節(jié)大小數(shù)組,需要將其轉(zhuǎn)換為動(dòng)態(tài)字節(jié)大小數(shù)組才能進(jìn)行轉(zhuǎn)換。

應(yīng)用中Hash string轉(zhuǎn)化為solidity的byte32數(shù)組

如果我們?cè)趎odeJs中使用某些算法獲得hash的string,例如IPFS的hash,如果智能合約的func的參數(shù)值設(shè)置為bytes32,那么我們就需要將這些hash值轉(zhuǎn)化成solidity的bytes32[]數(shù)組:

function ipfsHashToBytes32(ipfs_hash) {
    var h = bs58.decode(ipfs_hash).toString('hex').replace(/^1220/, '');
    if (h.length != 64) {
        console.log('invalid ipfs format', ipfs_hash, h);
        return null;
    }
    return '0x' + h;
}

function bytes32ToIPFSHash(hash_hex) {
    //console.log('bytes32ToIPFSHash starts with hash_buffer', hash_hex.replace(/^0x/, ''));
    var buf = new Buffer(hash_hex.replace(/^0x/, '1220'), 'hex')
    return bs58.encode(buf)
}

string?盡量不要用

最近,寫了點(diǎn)智能合約,想用string試一試,寫了一段頻繁更改map的value值的方法。

mapping (string=>uint) content;
mapping (address=>string) relation;
function temp(string hash, uint price) public {
        content[hash] = price;
        relation[msg.sender] = hash;
    }

結(jié)果運(yùn)行之后,出現(xiàn)了error:
Error: VM Exception while processing transaction: out of gas.
后來查閱了資料才發(fā)現(xiàn):
原來在solidity的contract中是一個(gè)非常昂貴的資源。盡量不要用,推薦使用固定長度的bytes數(shù)組來進(jìn)行替代。

bytes32

在編寫過程中,可能會(huì)有很多人從web3,remix以及eth wallet中獲得的bytes32值并不同。
比如說,合約:

pragma solidity ^0.4.11;

contract ABC{

    struct Data{
        bytes32 data;
        bytes32 data2;
        bytes32 data3;
        bytes32 data4;
        bytes32 data5;
    }
    mapping(uint => Data) public metaData;

    function ABC(){

    }

    function addData(bytes32 data,
        bytes32 data2,
        bytes32 data3,
        bytes32 data4,
        bytes32 data5){
        metaData[0]=Data(data,data2,data3,data4,data5);
    }

    function getData() returns(bytes32,bytes32,bytes32,bytes32,bytes32){
        return (metaData[0].data,metaData[0].data2,metaData[0].data3,metaData[0].data4,metaData[0].data5);
    }
}

輸入?yún)?shù):
"d4967590eb024589dfb6b9e48a576eb49ebc19d764b0d1d67dc21975e7258e97", "1", "1", "1", "065e0be95fb43db528a20ba65c0e575e33cd4a9e1ca089dba4efff24596e8553"

使用Remix:
[圖片上傳失敗...(image-d3e943-1523366258073)]
數(shù)據(jù)為:

0: bytes32: data 0x6434393637353930656230323435383964666236623965343861353736656234
1: bytes32: data2 0x3100000000000000000000000000000000000000000000000000000000000000
2: bytes32: data3 0x3100000000000000000000000000000000000000000000000000000000000000
3: bytes32: data4 0x3100000000000000000000000000000000000000000000000000000000000000
4: bytes32: data5 0x3036356530626539356662343364623532386132306261363563306535373565

以太坊wallet給出的數(shù)據(jù):


image.png

數(shù)據(jù)為原始數(shù)據(jù),但是每個(gè)數(shù)據(jù)都在之前加了一個(gè)0x。

0: bytes32: data 0xd4967590eb024589dfb6b9e48a576eb49ebc19d764b0d1d67dc21975e7258e97
1: bytes32: data2 0x1000000000000000000000000000000000000000000000000000000000000000
2: bytes32: data3 0x1000000000000000000000000000000000000000000000000000000000000000
3: bytes32: data4 0x1000000000000000000000000000000000000000000000000000000000000000
4: bytes32: data5 0x065e0be95fb43db528a20ba65c0e575e33cd4a9e1ca089dba4efff24596e8553

對(duì)于Web3.js
打印出來的數(shù)值和remix一樣,但是書順序變了,應(yīng)該是針對(duì)數(shù)值進(jìn)行了排序?

問題分析

因?yàn)閟olidity支持的bytes32,JavaScript并沒有原生的數(shù)據(jù)類型進(jìn)行支持。直接使用string并不能夠直接轉(zhuǎn)換到bytes32。推薦在直接傳遞byte數(shù)組給evm。如果我們想直接傳遞這個(gè)string,我們需要:

  • 為其添加一個(gè)0x十六進(jìn)制的前綴
  • 為其補(bǔ)齊(右靠齊)相對(duì)位數(shù)的0字符(64個(gè)字符)
    例如:
["0xd4967590eb024589dfb6b9e48a576eb49ebc19d764b0d1d67dc21975e7258e97",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"0x065e0be95fb43db528a20ba65c0e575e33cd4a9e1ca089dba4efff24596e8553"]

為了驗(yàn)證這個(gè)推斷,我們寫個(gè)小程序-string和hexStr(或者是byte數(shù)組)之間相互轉(zhuǎn)化的方法。然后測試一下:

string:
d4967590eb024589dfb6b9e48a576eb49ebc19d764b0d1d67dc21975e7258e97

hex:
64 34 39 36 37 35 39 30 65 62 30 32 34 35 38 39 64 66 62 36 62 39 65 34 38 61 35 37 36 65 62 34 39 65 62 63 31 39 64 37 36 34 62 30 64 31 64 36 37 64 63 32 31 39 37 35 65 37 32 35 38 65 39 37

所以,如果沒有將string添加0x前綴,默認(rèn)就會(huì)將其轉(zhuǎn)化為64 bytes數(shù)組。而且針對(duì)沒有滿足64bytes的情況,例如1。則會(huì)出現(xiàn)兩種情況

  • 將其視為0x31--也就是char 1。然后填充0來形成bytes32,或者是64位的hex數(shù)。
  • 直接將其視為hex數(shù)1,然后填充0來滿足bytes32.

參考鏈接

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 可變長度的字節(jié)數(shù)組 1.string 字符串可以通過" "或者' '來表示字符串的值,solidity中的stri...
    羅雪Melody閱讀 2,491評(píng)論 0 0
  • 翻譯原文date:20170617 Solidity是靜態(tài)類型語言,這意味著每個(gè)變量的類型必須在編譯的時(shí)候指定(或...
    gaoer1938閱讀 747評(píng)論 0 0
  • 保守療法就是理療針灸貼膏藥。 風(fēng)寒濕往往是膝痛發(fā)作的誘因,冬季應(yīng)加強(qiáng)局部保暖,夏季要注意空調(diào)的危害。 畏寒、疼...
    zl平安閱讀 356評(píng)論 0 1
  • #官僚制#讀到最后一章就讀不下去了
    未滿之都閱讀 172評(píng)論 0 0
  • 當(dāng)你下定決心做一件事 那就去盡力做 即便這件事最后沒有達(dá)到你的預(yù)期回報(bào) 但你還是得認(rèn)真 努力去完成 在這過程中 你...
    希sunflower虹閱讀 112評(píng)論 0 0

友情鏈接更多精彩內(nèi)容