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. windows批处理语法

    写批处理文件,除了了解基本语法外,你还需要熟悉常用的windows命令,那就先看看这篇文章:windows常用命令 #重要说明 文件及目录路径:要使用反斜杠'\',不要使用正斜杠'/' 如:del d ...

  2. 大部分人都会做错的经典JS闭包面试题

    由工作中演变而来的面试题 这是一个我工作当中的遇到的一个问题,似乎很有趣,就当做了一道题去面试,发现几乎没人能全部答对并说出原因,遂拿出来聊一聊吧. 先看题目代码: function fun(n,o) ...

  3. tangram2.6(XE2)\framework框架加载包异常 调试的地方

    添加以下的项目到项目组中, \tangram2.6(XE2)\framework\Core\Tangram_Core.dpk 调试此包的SysModuleMgr.pas的函数,本人还没有测试 func ...

  4. 【算法杂谈】LJX的迪杰斯特拉算法报告

    迪杰斯特拉(di jie qi)算法 这里有一张图: 假设要求从1号节点到5号节点的最短路.那么根据迪杰斯特拉算法的思想,我们先看: 节点1,从节点1出发的一共有3条路,分别是1-6.1-3.1-2. ...

  5. NoSQL-Redis【2】-HDEL给我的一个惊喜

    用HDEL删除Hash最后一个域的时候,Redis奇迹般的帮我清除了Key,真是考虑周到啊! 127.0.0.1:6673[2]> HMSET USER:Zhangshan Name 'Zhan ...

  6. ASP.NET Cache缓存的用法

    本文导读:在.NET运用中经常用到缓存(Cache)对象.有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序级别的 ...

  7. Python中的条件判断和循环

    1.使用elif代替else if,前者是后者的缩写. 2.所以for x in ...循环就是把每个元素代入变量x,然后执行缩进块的语句.   3.Python提供一个range()函数,可以生成一 ...

  8. *HDU 1054 二分图

    Strategic Game Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  9. Lua输入输出库

    1.简单模型 )1.io.write函数: 函数模型为io.write(...) )2.io.read函数: io.read(“*all”) 读取当前输入的整个文件 io.read(”*line“) ...

  10. html基本选择符的使用

    一.选择符在运用在CSS设计样式时对HTML的指定有至关重要的作用! 二.研究 普通选择符: 1.类型选择符:它可以选择同一个类型的元素! 例如:h1,h2 {              color: ...