我正在稳固地执行彩票智能合约,但是有时当我执行setWinner函数时会出错。有人可以告诉我为什么吗?

时间:2019-01-22 20:35:23

标签: solidity smartcontracts

我正在稳固地执行彩票智能合约,但是有时当我执行setWinner函数时会出错。有人可以告诉我为什么吗?我开始编程,所以我知道我的代码不是最好的,我接受一些建议。例如,选择一个随机数,我用时间戳的哈希值,然后分成8个部分,每个部分对应一个彩票游戏的一个数字。有没有更好的方法来做到这一点,而不是每次都将其除以二以获得一个随机数?

function setWinner() public {

    bytes32 hash = keccak256(abi.encode(block.timestamp));


    bytes4[2] memory x0 = [bytes4(0), 0];
    assembly {
        mstore(x0, hash)
        mstore(add(x0, 4), hash)
    }
    bytes4[2] memory x1 = [bytes4(0), 0];
    assembly {
        mstore(x1, hash)
        mstore(add(x1, 8), hash)
    }
    bytes4[2] memory x2 = [bytes4(0), 0];
    assembly {
        mstore(x2, hash)
        mstore(add(x2, 12), hash)
    }
    bytes4[2] memory x3 = [bytes4(0), 0];
    assembly {
        mstore(x3, hash)
        mstore(add(x3, 16), hash)
    }
    bytes4[2] memory x4 = [bytes4(0), 0];
    assembly {
        mstore(x4, hash)
        mstore(add(x4, 20), hash)
    }
    bytes4[2] memory x5 = [bytes4(0), 0];
    assembly {
        mstore(x5, hash)
        mstore(add(x5, 24), hash)
    }
    bytes4[2] memory x6 = [bytes4(0), 0];
    assembly {
        mstore(x6, hash)
        mstore(add(x6, 28), hash)
    }
    bytes4[2] memory x7 = [bytes4(0), 0];
    assembly {
        mstore(x7, hash)
        mstore(add(x7, 32), hash)
    }

    uint n0 = uint32 (x0[1]); 
    n0 = n0%numberMax;
    uint n1 = uint32 (x1[1]); 
    n1 = n1%numberMax;
    uint n2 = uint32 (x2[1]); 
    n2 = n2%numberMax;
    uint n3 = uint32 (x3[1]); 
    n3 = n3%numberMax;
    uint n4 = uint32 (x4[1]); 
    n4 = n4%numberMax;
    uint n5 = uint32 (x5[1]); 
    n5 = n5%numberMax;
    uint n6 = uint32 (x6[1]); 
    n6 = n6%numberMax;
    uint n7 = uint32 (x7[1]); 
    n7 = n7%numberMax;

    //emit numbersCheck(n0,n1,n2,n3,n4,n5,n6,n7);

    uint[qntNumbers] memory tabNumbers = [n0,n1,n2,n3,n4,n5,n6,n7];

    quickSort(tabNumbers,0,tabNumbers.length -1);
    //emit tabCheck(tabNumbers);

    /*for (uint i=0;i<tabNumbers.length;i++){

        if (tabNumbers[i]==0){
                tabNumbers[i]= 60;                
            }
        if ( (i <= tabNumbers.length)&& (tabNumbers[i]==tabNumbers[i+1])){

            tabNumbers[i+1]= tabNumbers[i+1] + 1;

        }
    }
    quickSort(tabNumbers,0,tabNumbers.length -1);*/
    //emit tabCheck(tabNumbers);
    removeDoubles(tabNumbers);

    winnerGame = tabNumbers;

}

1 个答案:

答案 0 :(得分:1)

block.timestamp是熵的不好来源。您应该避免使用它,以确保合同不受恶意参与者的侵害。

提交区块时,矿工会确定block.timestamp的值,因此可能会微不足道地影响彩票的结果。

您可能会提到这些类似的问题: