如何hash一个数字,并在一个solidity的智能合约中检查结果

想对一个数字进行哈希(在python中),然后使用solidity智能合约重新创建哈希,然后对该数字进行一些有用的操作。
目的是对数据进行签名并传递签名,然后使用ecrecover对其进行检查以验证数据。
hash一个字符串,并将其传递到合同中:


contract HashChecker {

    event LogI(int256);
    event LogA(address);
    event LogB(bytes32);
    event LogS(string);

    function HashChecker() {
    }

    function check_hash(string mystring, bytes32 expected_result_hash) {

        bytes32 result_hash = sha3(mystring);
        LogB(result_hash);
        LogB(expected_result_hash);

    }

}

测试的python代码:

from ethereum import tester
from sha3 import sha3_256

code1 = open('hash_checker_string.sol').read()
c1 = tester.state().abi_contract(code1, language='solidity')

print "Passing a string produces the sha3 I expect but I'm left with a string"

mystring = "foo"

c1.check_hash(
    "foo",
    sha3_256(mystring).hexdigest().decode('hex')
)

# Produces:
# {'': 'A\xb1\xa0d\x97R\xaf\x1b(\xb3\xdc)\xa1Un\xeex\x1eJL:\x1f\x7fS\xf9\x0f\xa84\xde\t\x8cM', '_event_type': 'LogB'}
# {'': 'A\xb1\xa0d\x97R\xaf\x1b(\xb3\xdc)\xa1Un\xeex\x1eJL:\x1f\x7fS\xf9\x0f\xa84\xde\t\x8cM', '_event_type': 'LogB'}



mynum = 123

code3 = open('hash_checker_int256.sol').read()
c3 = tester.state().abi_contract(code3, language='solidity')

print "This would be more useful if I could pass in an int, but that gives me a different hash"

c3.check_hash(
    mynum,
    sha3_256(hex(mynum)).hexdigest().decode('hex')
)

# Produces:
# {'': 'Ui\x04G\x19\xa1\xec;\x04\xd0\xaf\xa9\xe7\xa51\x0c|\x04s3\x1d\x13\xdc\x9f\xaf\xe1C\xb2\xc4\xe8\x14\x8a', '_event_type': 'LogB'}
# {'': '8\x84\x8a\xa0\xa2\xda\xd9\x8b|\x8c\xe9FE\x9e4&\x19>q\xeeC\x9c{\x0c\xeb-\xfba\\\xf4\x1d\xf9', '_event_type': 'LogB'}



code2 = open('hash_checker_bytes32.sol').read()
c2 = tester.state().abi_contract(code2, language='solidity')

print "Likewise with bytes"

c2.check_hash(
    mystring,
    sha3_256(mystring).hexdigest().decode('hex')
)

# Produces:
# {'': '\xca\x91\xe6I\x7f\xf2\xef\xafO\xfe\x80\xfa\xb4v\xcb|S\x99Y\xee5y\xed\x98~t\x85Xe\x9b\x97T', '_event_type': 'LogB'}
# {'': 'A\xb1\xa0d\x97R\xaf\x1b(\xb3\xdc)\xa1Un\xeex\x1eJL:\x1f\x7fS\xf9\x0f\xa84\xde\t\x8cM', '_event_type': 'LogB'}

想要:

a)在合约外重新创建得到的散列值

b)以在合约外创建hash的方式传数据进智能合约

c)将现在成功hash的字符串更改为合约中的byte32或int256

int:

sha3_256(decode_hex(format(mynum, 'x').zfill(64))).digest()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值