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. Android杂记:genymotion与eclipse报错问题

    用eclipse启动genymotion时有时候会报 The connection to adb is down, and a severe error has occured. You must r ...

  2. [Android Pro] listView和GridView的item设置的高度和宽度不起作用

    referece to : http://blog.csdn.net/beibeixiao/article/details/9032569 1.     在Android开发中会发现,有时listVi ...

  3. 无废话ExtJs 入门教程二十[数据交互:AJAX]

    无废话ExtJs 入门教程二十[数据交互:AJAX] extjs技术交流,欢迎加群(521711109) 1.代码如下: 1 <!DOCTYPE html PUBLIC "-//W3C ...

  4. cpp 4个类型转换

    static_cast.dynamic_cast.reinterpret_cast.const_cast 之间的区别 static_cast 用法:static_cast (expression) 说 ...

  5. 初学微信小程序

    最近微信推出了微信小程序,为此我学了几天,基本了解了组件及简单语法,但是今天我自己想要独立写一个demo时,忽然发现难道我的不是微信小程序的语法(我以前是iOS 开发,不用css),而是css样式的设 ...

  6. Unity4.0的使用

    最近公司用到了Unity,自己就研究了一下. 新建一个ASP.NET MVC基本项目,在NuGet上引入Unity4.0.1最新版. 因为我使用的项目为ASP.NET MVC,所以又添加一个Unity ...

  7. VR寒冬AR暖春,以色列AR公司再获3000万美元融资

    据统计,2015年国内至少有近70家VR公司获得天使或者A轮投资,不过狂欢并没有持续太久.2016年即将结束,资本寒冬和VR头盔的出货远不如预期,让投资者放慢了步伐,不过AR领域的热度依然不减.近日, ...

  8. Android入门(一):Android发展史

    Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发.尚未有统一中文名称,中国大陆地区较多人使用“安卓” ...

  9. mysql数据去除重复及相关优化(转)

    由于mysql不支持同时对一张表进行操作,即子查询和要进行的操作不能是同一张表,因此需要通过临时表中专以下. 1.单字段重复 生成临时表,其中uid是需要去重的字段 create table tmp_ ...

  10. 修改Windows Server 2008密码策略,设置简单密码

    最长使用期限为0表示密码永不过期. 如果是VBOX虚拟机安装,在使用共享文件夹功能时候,需要打开控制面板--网络和共享中心--共享设置--启动网络发现.然后才能映射共享文件夹