跳转到主要内容

下一代加密货币网络

项目描述

这是以太坊项目的Python核心库。

有关基于Python的命令行客户端,请参阅:https://github.com/ethereum/pyethapp

安装

sudo apt-get install libssl-dev build-essential automake pkg-config libtool libffi-dev libgmp-dev

git clone https://github.com/ethereum/pyethereum/

cd pyethereum

python setup.py install

组件

ethereum.pow.chain

包含Chain类,可用于管理区块链。主要方法有:

  • __init__(genesis=None, env=None, new_head_cb=None, reset_genesis=False, localtime=None) - 使用给定的创世纪初始化。 env指定环境(包括链配置和数据库),new_head_cb是当添加新头时调用的回调,localtime是链假设的当前时间戳。创世纪可以是:

    • None - 在这种情况下,它假定提供了env,并使用保存于env.db中的数据创建Chain对象。如果设置了reset_genesis,则重新初始化链。

    • State对象

    • 创世纪声明

    • 状态快照(State.snapshot()

    • 分配(即字典 {address: {balance: 1, nonce: 2, code: b'\x03\x04\x05', storage: {"0x06": "0x07"}}}

  • add_block(block) - 将区块添加到链中

  • process_time_queue(timestamp) - 通知链当前时间已增加到新的时间戳。然后,链将处理任何因为出现得太早而未处理的块。

  • get_blockhash_by_number(num) - 获取给定块号的块哈希。

  • get_block(hash) - 获取给定块哈希的块。

  • get_block_by_number(num) - 等价于 get_block(get_blockhash_by_number(num))

  • get_parent(block) - 获取块的父块。

  • get_children(block) - 获取块的子块。

  • head (属性) - 获取链头的块。

  • state (属性) - 获取链头的状态。

  • mk_poststate_of_blockhash(hash) - 在给定块之后创建一个状态对象。

  • has_block(block) - 该块是否在链中?返回 True/False。

  • get_chain(from, to) - 约等于 [get_block_by_number(i) for i in range(from, to)],但会自动停止如果达到头。 from 可以省略以从创世开始,to 可以省略以到达头。

  • get_tx_position(tx) - 如果交易在链中,则返回 (blknum, index),其中 blknum 是包含交易的块号,index 是其在块中的位置。

ethereum.state

包含用于管理状态的 State 类。主要方法有

  • __init__(root_hash, env, **kwargs) - 使用给定的根哈希、给定的 env(包括配置和数据库)以及给定的辅助参数初始化状态。这些包括

    • txindex - 交易索引

    • gas_used - 消耗的 gas 数量

    • gas_limit - 块 gas 限制

    • block_number - 块号

    • block_coinbase - 块 coinbase 地址

    • block_difficulty - 块难度

    • timestamp - 时间戳

    • logs - 已创建的日志

    • receipts - 已创建的收据(来自当前块中的先前交易)

    • bloom - bloom 过滤器

    • suicides - 自杀(或自我销毁,较新的、更政治正确的同义词)

    • recent_uncles - 链中的最近叔块

    • prev_headers - 上一块头信息

    • refunds - 自杀/自我销毁退款计数器

Pyethereum 采用 最大化状态模型;处理交易或块所需的信息全部位于状态本身中,使得实际状态转换逻辑非常简洁,为 apply_transaction(state, tx)apply_block(state, block)

  • get_balance- 获取账户的余额

  • get_code - 获取账户的代码

  • get_storage_data(addr, k) - 获取给定地址给定键的存储。期望键以 数字 形式(例如,b”cow” 或 “0x636f77” 表示为 6516599)。

  • to_snapshot(root_only=False, no_prevblocks=False) - 为当前状态创建快照。如果设置root_only,则只添加状态根,而不是整个状态。如果设置no_prevblocks,则不添加先前头和叔父。设置这两个标志之一意味着恢复快照需要相同的数据库。

  • from_snapshot(snapshot, env) (类方法) - 使用给定的env从快照创建状态。

  • ephemeral_clone() - 创建一个状态的副本,您可以在此工作而不会影响原始状态。

还有许多修改状态的方法,例如set_codeset_storage_data,但通常建议避免使用这些,而应仅通过apply_transactionapply_block来修改状态。

ethereum.meta

此文件包含两个函数

  • apply_block(state, block) - 将块处理到给定的状态中

  • make_head_candidate(chain, txqueue=None, parent=None, timestamp, coinbase, extra_data, min_gasprice=0) - 在给定的父块(默认:链的头部)之上创建链的候选块。从给定的txqueue对象获取交易,具有给定的mingasprice(否则不添加交易)。可以使用timestampcoinbaseextra_data来指定块中的这些参数;否则使用默认值

ethereum.messages

应从此处调用的主要函数是apply_transaction(state, tx)

ethereum.utils

包含许多实用函数,包括

数值和十六进制转换

  • encode_int(i) - 将整数转换为大端二进制表示

  • zpad(data, length) - 通过在左侧添加零字节将数据填充到所需长度

  • encode_int32(i) - 等同于zpad(encode_int(i), 32)但更快

  • big_endian_to_int(d) - 将二进制数据转换为整数

  • encode_hex(b) - 将字节转换为十六进制

  • decode_hex(h) - 将十六进制转换为字节

  • int_to_addr(i) - 将整数转换为地址

  • is_numeric(i) - 如果值是int或long,则返回True,否则返回False

密码学

  • sha3(data) - 计算SHA3(或更确切地说是keccak256)哈希

  • ecrecover_to_pub(hash, v, r, s) - 从签名恢复创建签名的公钥,作为64字节的二进制blobencode_int32(x) + encode_int32(y)。计算此哈希并取最后20字节给出签名消息的地址

  • ecsign(hash, key) - 返回签名的v、r、s值

  • normalize_key(key) - 将密钥从许多格式转换为32字节二进制

  • privtoaddr(key) - 将密钥转换为地址

地址

  • normalize_address(addr) - 将地址转换为20字节二进制形式

  • check_checksum(addr) - 如果地址校验和通过,则返回True,否则返回False

  • checksum_encode(addr) - 将地址转换为带校验和的十六进制形式

  • mk_contract_address(addr, nonce) - 创建由给定地址和给定nonce创建的合约的地址

杂项

  • denoms - 包含以太币的面值,例如:denoms.finney = 10**15denoms.shannon = 10**9denoms.gwei = 10**9

ethereum.block

包含 BlockBlockHeader 类。通常建议避免直接创建块和块头部,而是使用 mk_head_candidate。成员变量很简单

  • block.transactions - 块中的交易

  • block.uncles - 块中的叔父块

  • block.header - 块的头部

并在头部中

  • header.hash - 哈希(也是块哈希)

  • header.mining_hash - 用于工作量证明挖掘的哈希

  • header.to_dict() - 序列化为可读的字典

  • header.prevhash - 前一个块哈希

  • header.uncles_hash - 叔父列表的哈希

  • header.coinbase - coinbase(矿工)地址

  • header.state_root - 后状态根哈希

  • header.tx_list_root - 块中交易的哈希

  • header.receipts_root - 收据trie的哈希

  • header.bloom - bloom过滤器

  • header.difficulty - 块难度

  • header.number - 块编号

  • header.gas_limit - 气量限制

  • header.gas_used - 消耗的气量

  • header.timestamp - 时间戳

  • header.extra_data - 块额外数据

  • header.mixhashheader.nonce - Ethash工作量证明值

ethereum.transactions

包含 Transaction 类,具有以下方法和值

  • __init__(nonce, gasprice, startgas, to, value, data, (v, r, s optional)) - 构造函数

  • sign(key, network_id=None) - 使用给定的密钥对交易进行签名,并使用给定的 EIP155 链 ID(如果留为 None,将创建一个 EIP155 之前的交易,请注意这种操作可能导致重放攻击!)

  • sender - 交易的发送者地址

  • network_id - 交易的 EIP155 链 ID

  • hash - 交易的哈希

  • to_dict() - 序列化为可读的字典

  • intrinsic_gas_used - 交易消耗的气量,包括交易数据的费用

  • creates - 如果交易创建了一个合约,则返回合约地址

  • noncegaspricestartgastovaluedatavrs - 交易中的参数

ethereum.tools.keys

创建加密私钥存储

  • decode_keystore_json(jsondata, password) - 从加密的 keystore 对象中返回私钥。注意:如果您从文件中加载,最方便的方法是 import json; key = decode_keystore_json(json.load(open('filename.json')), 'password')

  • make_keystore_json(key, pw, kdf='pbkdf2', cipher='aes-128-ctr') - 为密钥创建加密的 keystore 对象。建议保持 kdfcipher 的默认值。

ethereum.abi

Ethereum 上大多数用于高级语言的编译器(如 Solidity、Serpent、Viper 等)都提供输出程序 ABI 声明的选项。这是一个类似下面的 JSON 对象:

[{"name": "ecrecover(uint256,uint256,uint256,uint256)", "type": "function", "constant": false,
 "inputs": [{"name": "h", "type": "uint256"}, {"name": "v", "type": "uint256"}, {"name": "r", "type": "uint256"}, {"name": "s", "type": "uint256"}],
 "outputs": [{"name": "out", "type": "int256[]"}]},
 {"name": "PubkeyTripleLogEvent(uint256,uint256,uint256)", "type": "event",
 "inputs": [{"name": "x", "type": "uint256", "indexed": false}, {"name": "y", "type": "uint256", "indexed": false}, {"name": "z", "type": "uint256", "indexed": false}]}]

您可以初始化一个 abi.ContractTranslator 对象,如下编码和解码合约数据:

true, false = True, False
ct = abi.ContractTranslator(<json here>)
txdata = ct.encode('function_name', [arg1, arg2, arg3])

您还可以调用 ct.decode_event([topic1, topic2...], logdata) 来解码日志。

RLP 编码和解码

对于任何交易或块,您可以这样做:

import rlp
bindata = rlp.encode(<tx or block>)

解码

import rlp
from ethereum.transactions import Transaction
rlp.decode(blob, Transaction)

或者

import rlp
from ethereum.blocks import Block
rlp.decode(blob, Block)

共识抽象

pyethereum 代码库旨在对许多不同的共识算法提供最大程度的友好性。如果您想添加新的共识算法,您需要采取以下步骤:

  • pow 旁边添加一个目录,并在其中创建一个实现 Chain 模块的 chain.py 类。这可能会有完全不同的工作量证明(GHOST、签名计数、Casper 等)分叉选择规则。

  • consensus_strategy.py 中添加一个条目。您需要实现以下内容:

    • check_seal - 检查一个块是否被正确“密封”(挖矿、签名等)

    • validate_uncles(state, block) - 检查叔父是否有效

    • initialize(state, block) - 在处理交易之前在 apply_block 中调用

    • finalize(state, block) - 在处理交易后在 apply_block 中调用

    • get_uncle_candidates(chain, state) - 在 mk_head_candidate 中调用以在块中包含叔父

  • 创建一个带有 CONSENSUS_STRATEGY 设置为您的全新共识策略名称的链配置

Tester 模块

请参阅 https://github.com/ethereum/pyethereum/wiki/Using-pyethereum.tester

测试

运行 python3.6 -m pytest ethereum/tests/<filename> 来运行该目录中任何 .py 文件。目前所有测试都通过,除了几个 Metropolis 特定的状态测试和块测试。

要创建自己的状态测试,请使用 tester 模块如下:

from ethereum.tools import tester as t
import json
c = t.Chain()
x = c.contract(<code>, language=<language>)
pre = t.mk_state_test_prefill(c)
x.foo(<args>)
post = t.mk_state_test_postfill(c, pre)
open('output.json', 'w').write(json.dumps(post, indent=4))

要创建一个测试填充文件,请执行 post = t.mk_state_test_postfill(c, pre, True)

许可

请参阅 LICENSE

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

ethereum-augur-temp2-2.0.6.tar.gz (138.8 kB 查看哈希)

上传时间

构建分布

ethereum_augur_temp2-2.0.6-py2-none-any.whl (166.2 kB 查看哈希)

上传时间 Python 2

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面