首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算python中的ethash?

如何计算python中的ethash?
EN

Ethereum用户
提问于 2018-10-22 10:31:16
回答 1查看 1.6K关注 0票数 0

我试图用ethash(hash(blockHeader),nonce) < TARGET来证明这个区块至少有一个最小的难度。

以上公式正确吗?

当我尝试使用ehtereum.pow.ethash的时候:

代码语言:javascript
复制
from ethereum.pow import ethash
difficulty = 3963642329
block_number = 4156209
nonce = int('0xf245822d3412da7f', 16)
block_hash = 0x47b8f62c1400dae65105d2f8e03824bfc58481c0b32f45788ad3378fbc05e9f6
cache = ethash.mkcache(block_number)
ethash = hashimoto_light(block_number, cache, block_hash, nonce)
print(ethash)

我知道这个错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    cache = ethash.mkcache(block_number)
  File "(environment_path)/lib/python3.6/site-packages/ethereum/pow/ethash.py", line 15, in mkcache
    while len(cache_seeds) <= block_number // EPOCH_LENGTH:
NameError: name 'EPOCH_LENGTH' is not defined

我做错了吗?或者ethereum.pow.ethash中有一个bug?

EN

回答 1

Ethereum用户

回答已采纳

发布于 2018-10-22 20:13:46

没有维护ethereum模块。出于同样的目的,请查看pyethash

你可以像这样进口:

代码语言:javascript
复制
from pyethash import (
    EPOCH_LENGTH,
    hashimoto_light,
    mkcache_bytes,
)

py-evm用它来检查工作证明是这样的:

代码语言:javascript
复制
def check_pow(block_number: int,
              mining_hash: Hash32,
              mix_hash: Hash32,
              nonce: bytes,
              difficulty: int) -> None:
    validate_length(mix_hash, 32, title="Mix Hash")
    validate_length(mining_hash, 32, title="Mining Hash")
    validate_length(nonce, 8, title="POW Nonce")
    cache = get_cache(block_number)
    mining_output = hashimoto_light(
        block_number, cache, mining_hash, big_endian_to_int(nonce))
    if mining_output[b'mix digest'] != mix_hash:
        raise ValidationError("mix hash mismatch; {0} != {1}".format(
            encode_hex(mining_output[b'mix digest']), encode_hex(mix_hash)))
    result = big_endian_to_int(mining_output[b'result'])
    validate_lte(result, 2**256 // difficulty, title="POW Difficulty")

其中产生和存储缓存。具有:

代码语言:javascript
复制
# Type annotation here is to ensure we don't accidentally use strings instead of bytes.
cache_seeds = [b'\x00' * 32]  # type: List[bytes]
cache_by_seed = OrderedDict()  # type: OrderedDict[bytes, bytearray]
CACHE_MAX_ITEMS = 10


def get_cache(block_number: int) -> bytes:
    while len(cache_seeds) <= block_number // EPOCH_LENGTH:
        cache_seeds.append(keccak(cache_seeds[-1]))
    seed = cache_seeds[block_number // EPOCH_LENGTH]
    if seed in cache_by_seed:
        c = cache_by_seed.pop(seed)  # pop and append at end
        cache_by_seed[seed] = c
        return c
    c = mkcache_bytes(block_number)
    cache_by_seed[seed] = c
    if len(cache_by_seed) > CACHE_MAX_ITEMS:
        cache_by_seed.popitem(last=False)  # remove last recently accessed
    return c
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/60986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档