def calc_difficulty(parent, timestamp):
config = parent.config
offset = parent.difficulty // config['BLOCK_DIFF_FACTOR']
if parent.number >= (config['METROPOLIS_FORK_BLKNUM'] - 1):
sign = max(len(parent.uncles) - ((timestamp - parent.timestamp) // config['METROPOLIS_DIFF_ADJUSTMENT_CUTOFF']), -99)
elif parent.number >= (config['HOMESTEAD_FORK_BLKNUM'] - 1):
sign = max(1 - ((timestamp - parent.timestamp) // config['HOMESTEAD_DIFF_ADJUSTMENT_CUTOFF']), -99)
else:
sign = 1 if timestamp - parent.timestamp < config['DIFF_ADJUSTMENT_CUTOFF'] else -1
# If we enter a special mode where the genesis difficulty starts off below
# the minimal difficulty, we allow low-difficulty blocks (this will never
# happen in the official protocol)
o = int(max(parent.difficulty + offset * sign, min(parent.difficulty, config['MIN_DIFF'])))
period_count = (parent.number + 1) // config['EXPDIFF_PERIOD']
if period_count >= config['EXPDIFF_FREE_PERIODS']:
o = max(o + 2 ** (period_count - config['EXPDIFF_FREE_PERIODS']), config['MIN_DIFF'])
# print('Calculating difficulty of block %d, timestamp difference %d, parent diff %d, child diff %d' % (parent.number + 1, timestamp - parent.timestamp, parent.difficulty, o))
return o

  以上方法计算困难度

一个以太坊账号的类(Account):

内部的属性:

    """
在这个类Account的参数列表中有一个参数rlp.Serializeable,应该表示一个经过序列化后的rlp编码格式的对象字符
:ivar nonce:一个账户的nonce(表示这个账户的交易数目)
:ivar balance:这个账户的余额
:ivar storage: 表示这个账户的tire的根
:ivar code_hash: 表示和账户关联的经过SHA3的哈希串
""" fields = [
('nonce', big_endian_int),
('balance', big_endian_int),
('storage', trie_root),
('code_hash', hash32)
]

该类的_init_方法参数列表(self, nonce, balance, storage, code_hash, db),初始化方法如下,使用

 def __init__(self, nonce, balance, storage, code_hash, db):
assert isinstance(db, BaseDB)
self.db = db
super(Account, self).__init__(nonce, balance, storage, code_hash)

以下获得code值,方法如下:(code指什么?codehash?)

    @property
def code(self):
"""The EVM code of the account. This property will be read from or written to the db at each access,
with :ivar:`code_hash` used as key.
"""
return self.db.get(self.code_hash)

以下设置code的值

@code.setter
def code(self, value):
self.code_hash = utils.sha3(value)
# Technically a db storage leak, but doesn't really matter; the only
# thing that fails to get garbage collected is when code disappears due
# to a suicide
self.db.inc_refcount(self.code_hash, value)

下面方法设置一个空白账户:

    @classmethod
def blank_account(cls, db, initial_nonce=0):
"""Create a blank account The returned account will have zero nonce and balance, a blank storage
trie and empty code. :param db: the db in which the account will store its code.
"""
code_hash = utils.sha3(b'')
db.put(code_hash, b'')
return cls(initial_nonce, 0, trie.BLANK_ROOT, code_hash, db)

类Receipt

#state_root用于对数据库进行校验,当和其他数据库不一致的时候,表明有非法交易或者需要同步,用于校验
fields = [
('state_root', trie_root),
('gas_used', big_endian_int),
('bloom', int256),
('logs', CountableList(processblock.Log))
]

类blockhead

他的类内的属性为:

fields = [
('prevhash', hash32), //前一个block的32字节hash值
('uncles_hash', hash32), // 32字节的 经过RLP编码的uncle headers的列表
('coinbase', address), //20字节的coinbase字节的地址
('state_root', trie_root), // state trie的根
('tx_list_root', trie_root), //
('receipts_root', trie_root),
('bloom', int256),
('difficulty', big_endian_int), //区块的难度
('number', big_endian_int), //区块祖先的个数
('gas_limit', big_endian_int),
('gas_used', big_endian_int), //这个区块上所有的交易消耗的gas
('timestamp', big_endian_int),
('extra_data', binary), ///最多1024字节
('mixhash', binary),
('nonce', Binary(8, allow_empty=True)) //32字节 作为占位符或者去构成工作量证明
]

  这些属性的初始化如下:

 def __init__(self,
prevhash=default_config['GENESIS_PREVHASH'], //default 在etherum下的config包中 GENESIS_PREVHASH=b'\x00' * 32,
uncles_hash=utils.sha3rlp([]),
coinbase=default_config['GENESIS_COINBASE'],//GENESIS_COINBASE=b'\x00' * 20,
state_root=trie.BLANK_ROOT,
tx_list_root=trie.BLANK_ROOT,
receipts_root=trie.BLANK_ROOT,
bloom=0,
difficulty=default_config['GENESIS_DIFFICULTY'],
number=0,
gas_limit=default_config['GENESIS_GAS_LIMIT'], //GENESIS_GAS_LIMIT=3141592
gas_used=0,
timestamp=0,
extra_data='',
mixhash=default_config['GENESIS_MIXHASH'],
nonce=''):
# at the beginning of a method, locals() is a dict of all arguments
fields = {k: v for k, v in locals().items() if k != 'self'}
if len(fields['coinbase']) == 40:
fields['coinbase'] = decode_hex(fields['coinbase'])
assert len(fields['coinbase']) == 20
self.block = None
super(BlockHeader, self).__init__(**fields)

  

  

源码阅读 etherum-block.py的更多相关文章

  1. Robot Framework 源码阅读 day1 run.py

    robot里面run起来的接口主要有两类 run_cli def run_cli(arguments): """Command line execution entry ...

  2. Robot Framework 源码阅读 day1 __main__.py

    robot文件夹下的__main__.py函数 是使用module运行时的入口函数: import sys # Allows running as a script. __name__ check n ...

  3. Mask RCNN 源码阅读(update)

    之前看了Google官网的object_dectect 的源码,感觉Google大神写的还不错.最近想玩下Mask RCNN,就看了下源码,这里刚好当做总结和梳理.链接如下: Google官网的obj ...

  4. Pytorch版本yolov3源码阅读

    目录 Pytorch版本yolov3源码阅读 1. 阅读test.py 1.1 参数解读 1.2 data文件解析 1.3 cfg文件解析 1.4 根据cfg文件创建模块 1.5 YOLOLayer ...

  5. python3 源码阅读-虚拟机运行原理

    阅读源码版本python 3.8.3 参考书籍<<Python源码剖析>> 参考书籍<<Python学习手册 第4版>> 官网文档目录介绍 Doc目录主 ...

  6. 【原】FMDB源码阅读(三)

    [原]FMDB源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 FMDB比较优秀的地方就在于对多线程的处理.所以这一篇主要是研究FMDB的多线程处理的实现.而 ...

  7. 【原】FMDB源码阅读(二)

    [原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...

  8. 【原】AFNetworking源码阅读(六)

    [原]AFNetworking源码阅读(六) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 这一篇的想讲的,一个就是分析一下AFSecurityPolicy文件,看看AF ...

  9. 【原】AFNetworking源码阅读(五)

    [原]AFNetworking源码阅读(五) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中提及到了Multipart Request的构建方法- [AFHTTP ...

  10. 【原】AFNetworking源码阅读(四)

    [原]AFNetworking源码阅读(四) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇还遗留了很多问题,包括AFURLSessionManagerTaskDe ...

随机推荐

  1. java冒泡排序

    public class BubbleSort { public static void main(String[] args) { int score[] = {1,4,5,7,2,3,9,0,6, ...

  2. error LNK2019:unresolved external symbol

    error LNK2019:unresolved external symbol 这个错误是指程序不认识函数.具体的说就是.h文件中定义并没有实现,这就是库出现了问题. 遇到这个问题,第一步就要看是哪 ...

  3. Android Studio增加NDK代码编译支持--Mac环境

    Android的APP开发基本都是使用Java或者跨平台框架进行开发的,对于很多APP来说已经足够了,但是,对于提供功能给外部使用或者性能要求很高的需求下,如图像处理等,可能会需要C/C++库的支持, ...

  4. error-unable-to-access-the-iis-metabase或者无法加载VS项目中的网站

    参考:http://stackoverflow.com/questions/12859891/error-unable-to-access-the-iis-metabase 1.确定IIS是否安装完整 ...

  5. C++ 定义全局数组

    数组怎么用,全局数组就怎么用,只是他的作用域不一样才叫全局数组... 在A.h 或 A.cpp中定义char buf[10]; 如果在B.cpp要用,就在其开头中写成 extern char buf[ ...

  6. CentOS7中DHCP配置

    因为需要网络引导系统的安装,所以需要安装和配置DHCP服务器.DHCP(Dynamic Host Configuration Protocol) 动态主机配置协议,它提供了一种动态指定IP地址和配置参 ...

  7. iOS AFOAuth2Manager使用心得

    github地址:  https://github.com/AFNetworking/AFOAuth2Manager 这个库,不多说,实现OAuth 2.0授权访问. 确实可以减轻很大的负担,而且使用 ...

  8. 归一化交叉相关Normalization cross correlation (NCC)

    归一化交叉相关Normalization cross correlation (NCC) 相关系数,图像匹配 NCC正如其名字,是用来描述两个目标的相关程度的,也就是说可以用来刻画目标间的相似性.一般 ...

  9. Gitbook简易教程

    简介 GitBook 是一个基于 Node.js 的命令行工具,可使用 Github/Git 和 Markdown 来制作精美的电子书.GitBook支持输出以下几种文档格式 静态站点:GitBook ...

  10. [我的试题]Test of String

    1.前言 这是我出的第一套题目,话说感觉有点晚了,还是在向总安排下出的.我被安排的是字符串方面的内容,这应该相对而言是比较小众的知识点吧,但是一样的有作用的,也有很神的题目.所谓是NOIP模拟题,其实 ...