之前可以先了解一下另一个模块,看本博客的ethereumjs/ethereumjs-common部分内容

通过tests测试文件能够帮助更好了解API的使用

ethereumjs-block/tests/header.js

const tape = require('tape')
const Common = require('ethereumjs-common')
const utils = require('ethereumjs-util')
const rlp = utils.rlp
const Header = require('../header.js')
const Block = require('../index.js') tape('[Block]: Header functions', function (t) {
t.test('should create with default constructor', function (st) {
function compareDefaultHeader (st, header) {
st.deepEqual(header.parentHash, utils.zeros())
st.equal(header.uncleHash.toString('hex'), utils.SHA3_RLP_ARRAY_S)
st.deepEqual(header.coinbase, utils.zeros())
st.deepEqual(header.stateRoot, utils.zeros())
st.equal(header.transactionsTrie.toString('hex'), utils.SHA3_RLP_S)
st.equal(header.receiptTrie.toString('hex'), utils.SHA3_RLP_S)
st.deepEqual(header.bloom, utils.zeros())
st.deepEqual(header.difficulty, Buffer.from([]))
st.deepEqual(header.number, utils.intToBuffer())
st.deepEqual(header.gasLimit, Buffer.from('ffffffffffffff', 'hex'))
st.deepEqual(header.gasUsed, Buffer.from([]))
st.deepEqual(header.timestamp, Buffer.from([]))
st.deepEqual(header.extraData, Buffer.from([]))
st.deepEqual(header.mixHash, utils.zeros())
st.deepEqual(header.nonce, utils.zeros())
} var header = new Header()
compareDefaultHeader(st, header) var block = new Block()
header = block.header
compareDefaultHeader(st, header) st.end()
}) t.test('should test header initialization', function (st) {
const header1 = new Header(null, { 'chain': 'ropsten' }) //初始化,一种是提供chain/hardfork
const common = new Common('ropsten')
const header2 = new Header(null, { 'common': common })//另一种则是使用common,common和chain不能同时提供,会报错
header1.setGenesisParams()//就是将该区块头设置为规范初始区块头
header2.setGenesisParams()
st.strictEqual(header1.hash().toString('hex'), header2.hash().toString('hex'), 'header hashes match')//因为两个都设置为规范初始区块头,所以相应的值是相同的 st.throws(function () { new Header(null, { 'chain': 'ropsten', 'common': common }) }, /not allowed!$/, 'should throw on initialization with chain and common parameter') // eslint-disable-line
st.end()
}) t.test('should test validateGasLimit', function (st) {//对gasLimit进行验证
const testData = require('./bcBlockGasLimitTest.json').tests
const bcBlockGasLimigTestData = testData.BlockGasLimit2p63m1 Object.keys(bcBlockGasLimigTestData).forEach(key => {
var parentBlock = new Block(rlp.decode(bcBlockGasLimigTestData[key].genesisRLP)) //使用genesisRLP初始化block得到的是父区块
var block = new Block(rlp.decode(bcBlockGasLimigTestData[key].blocks[].rlp)) //使用blocks[0].rlp初始化block得到的是本区块
st.equal(block.header.validateGasLimit(parentBlock), true)
}) st.end()
}) t.test('should test isGenesis', function (st) {
var header = new Header() //查看该区块头是否为初始区块
st.equal(header.isGenesis(), false)
header.number = Buffer.from([]) //通过设置header.number为空buffer数组就能得到是初始区块的结果
st.equal(header.isGenesis(), true)
st.end()
}) const testDataGenesis = require('./genesishashestest.json').test
t.test('should test genesis hashes (mainnet default)', function (st) {
var header = new Header()
header.setGenesisParams()
st.strictEqual(header.hash().toString('hex'), testDataGenesis.genesis_hash, 'genesis hash match')
st.end()
}) t.test('should test genesis parameters (ropsten)', function (st) {
var genesisHeader = new Header(null, { 'chain': 'ropsten' })
genesisHeader.setGenesisParams()
let ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b'
st.strictEqual(genesisHeader.stateRoot.toString('hex'), ropstenStateRoot, 'genesis stateRoot match')
st.end()
})
})

ethereumjs-block/tests/block.js

const tape = require('tape')
const Common = require('ethereumjs-common')
const rlp = require('ethereumjs-util').rlp
const Block = require('../index.js') tape('[Block]: block functions', function (t) {
t.test('should test block initialization', function (st) {
const block1 = new Block(null, { 'chain': 'ropsten' }) //初始化,一种是提供chain/hardfork
const common = new Common('ropsten')
const block2 = new Block(null, { 'common': common })//另一种则是使用common,common和chain不能同时提供,会报错
block1.setGenesisParams()//就是将该区块设置为规范初始区块
block2.setGenesisParams()
st.strictEqual(block1.hash().toString('hex'), block2.hash().toString('hex'), 'block hashes match')//因为两个都设置为规范初始区块,所以相应的值是相同的 st.throws(function () { new Block(null, { 'chain': 'ropsten', 'common': common }) }, /not allowed!$/, 'should throw on initialization with chain and common parameter') // eslint-disable-line
st.end()
}) const testData = require('./testdata.json') function testTransactionValidation (st, block) {
st.equal(block.validateTransactions(), true) //验证区块中的交易 block.genTxTrie(function () {//必须要先生成了前缀树后才能调用验证前缀树的操作
st.equal(block.validateTransactionsTrie(), true)
st.end()
})
} t.test('should test transaction validation', function (st) {
var block = new Block(rlp.decode(testData.blocks[].rlp))
st.plan()
testTransactionValidation(st, block)
}) t.test('should test transaction validation with empty transaction list', function (st) {
var block = new Block()
st.plan()
testTransactionValidation(st, block)
}) const testData2 = require('./testdata2.json')
t.test('should test uncles hash validation', function (st) {
var block = new Block(rlp.decode(testData2.blocks[].rlp))//从区块信息文件生成相同区块
st.equal(block.validateUnclesHash(), true)//验证该区块的叔块hash
st.end()
}) t.test('should test isGenesis (mainnet default)', function (st) {
var block = new Block()
st.notEqual(block.isGenesis(), true) //查看是否为初始区块,为false
block.header.number = Buffer.from([])//决定因素是block.header.number,设置为空数组buffer即可
st.equal(block.isGenesis(), true)
st.end()
}) t.test('should test isGenesis (ropsten)', function (st) {
var block = new Block(null, { 'chain': 'ropsten' })
st.notEqual(block.isGenesis(), true)
block.header.number = Buffer.from([])
st.equal(block.isGenesis(), true)
st.end()
}) const testDataGenesis = require('./genesishashestest.json').test//(初始区块信息)
t.test('should test genesis hashes (mainnet default)', function (st) {
var genesisBlock = new Block()
genesisBlock.setGenesisParams()//设置为初始区块
var rlp = genesisBlock.serialize() //序列化,就是将其生产rlp格式
st.strictEqual(rlp.toString('hex'), testDataGenesis.genesis_rlp_hex, 'rlp hex match')
st.strictEqual(genesisBlock.hash().toString('hex'), testDataGenesis.genesis_hash, 'genesis hash match')
st.end()
}) t.test('should test genesis hashes (ropsten)', function (st) {
var common = new Common('ropsten')
var genesisBlock = new Block(null, { common: common })
genesisBlock.setGenesisParams()
st.strictEqual(genesisBlock.hash().toString('hex'), common.genesis().hash.slice(), 'genesis hash match')
st.end()
}) t.test('should test genesis hashes (rinkeby)', function (st) {
var common = new Common('rinkeby')
var genesisBlock = new Block(null, { common: common })
genesisBlock.setGenesisParams()
st.strictEqual(genesisBlock.hash().toString('hex'), common.genesis().hash.slice(), 'genesis hash match')
st.end()
}) t.test('should test genesis parameters (ropsten)', function (st) {
var genesisBlock = new Block(null, { 'chain': 'ropsten' })
genesisBlock.setGenesisParams()
let ropstenStateRoot = '217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b'
st.strictEqual(genesisBlock.header.stateRoot.toString('hex'), ropstenStateRoot, 'genesis stateRoot match')
st.end()
}) t.test('should test toJSON', function (st) {
var block = new Block(rlp.decode(testData2.blocks[].rlp))
st.equal(typeof (block.toJSON()), 'object') //返回值为object类型
st.equal(typeof (block.toJSON(true)), 'object')
st.end()
})
})

ethereumjs-block/tests/difficulty.js

const utils = require('ethereumjs-util')
const tape = require('tape')
const Block = require('../')
const BN = utils.BN function normalize (data) {
Object.keys(data).map(function (i) {
if (i !== 'homestead' && typeof (data[i]) === 'string') {
data[i] = utils.isHexPrefixed(data[i]) ? new BN(utils.toBuffer(data[i])) : new BN(data[i])
}
})
} tape('[Header]: difficulty tests', t => {
function runDifficultyTests (test, parentBlock, block, msg) {
normalize(test) var dif = block.header.canonicalDifficulty(parentBlock)//返回区块的规范困难度
t.equal(dif.toString(), test.currentDifficulty.toString(), `test canonicalDifficulty (${msg})`) //从父区块得到的规范困难度与当前区块的困难度应该是相等的
t.assert(block.header.validateDifficulty(parentBlock), `test validateDifficulty (${msg})`) //查看区块头是否符合规范困难度的区块困难度
} const hardforkTestData = {
'chainstart': require('./difficultyFrontier.json').tests,
'homestead': require('./difficultyHomestead.json').tests,
'byzantium': require('./difficultyByzantium.json').tests,
'constantinople': require('./difficultyConstantinople.json').tests
}
for (let hardfork in hardforkTestData) {
const testData = hardforkTestData[hardfork]
for (let testName in testData) {
let test = testData[testName]
let parentBlock = new Block(null, { 'chain': 'mainnet', 'hardfork': hardfork })
parentBlock.header.timestamp = test.parentTimestamp
parentBlock.header.difficulty = test.parentDifficulty
parentBlock.header.uncleHash = test.parentUncles let block = new Block(null, { 'chain': 'mainnet', 'hardfork': hardfork })
block.header.timestamp = test.currentTimestamp
block.header.difficulty = test.currentDifficulty
block.header.number = test.currentBlockNumber runDifficultyTests(test, parentBlock, block, 'fork determination by hardfork param')
}
} const chainTestData = {
'mainnet': require('./difficultyMainNetwork.json').tests,
'ropsten': require('./difficultyRopstenByzantium.json').tests
}
for (let chain in chainTestData) {
const testData = chainTestData[chain]
for (let testName in testData) {
let test = testData[testName]
let parentBlock = new Block(null, { 'chain': chain })
parentBlock.header.timestamp = test.parentTimestamp
parentBlock.header.difficulty = test.parentDifficulty
parentBlock.header.uncleHash = test.parentUncles let block = new Block(null, { 'chain': chain })
block.header.timestamp = test.currentTimestamp
block.header.difficulty = test.currentDifficulty
block.header.number = test.currentBlockNumber runDifficultyTests(test, parentBlock, block, 'fork determination by block number')
}
} t.end()

ethereumjs/ethereumjs-block-3-tests的更多相关文章

  1. ethereumjs/ethereumjs-block-1-简介

    https://github.com/ethereumjs/ethereumjs-block Encoding, decoding and validation of Ethereum's Block ...

  2. NGINX Load Balancing – TCP and UDP Load Balancer

    This chapter describes how to use NGINX Plus and open source NGINX to proxy and load balance TCP and ...

  3. CSS动画划入划出酷炫

    HTML插入 <!DOCTYPE html> <html class="no-js iarouse"> <head> <meta char ...

  4. ethereumjs/ethereumjs-vm-4-tests

    根据代码发现还要了解的模块有: ethereumjs/merkle-patricia-tree -对应数据存储的数据结构 ethereumjs-blockchain —— 区块链 ethereumjs ...

  5. ethereumjs/ethereumjs-block-2-api

    https://github.com/ethereumjs/ethereumjs-block/blob/master/docs/index.md 详细的调用代码可见本博客的ethereumjs/eth ...

  6. ethereumjs/ethereumjs-blockchain-2-test

    https://github.com/ethereumjs/ethereumjs-blockchain/tree/master/test 'use strict' const test = requi ...

  7. ethereumjs/ethereumjs-blockchain-1-简介和API

    https://github.com/ethereumjs/ethereumjs-blockchain SYNOPSIS概要 A module to store and interact with b ...

  8. ethereumjs/ethereumjs-wallet

    Utilities for handling Ethereum keys ethereumjs-wallet A lightweight wallet implementation. At the m ...

  9. ethereumjs/ethereumjs-common-1-简介

    为了了解ethereumjs/ethereumjs-block-3-代码的使用需要了解的一个模块 https://github.com/ethereumjs/ethereumjs-common Com ...

随机推荐

  1. 七、spark核心数据集RDD

    简介 spark RDD操作具体参考官网:http://spark.apache.org/docs/latest/rdd-programming-guide.html#overview RDD全称叫做 ...

  2. JRE“瘦身”&桌面程序集成JRE

    项目是一个桌面程序,程序文件不大,但运行jre有198 MB,因此需要"瘦身". jre包含bin.lib两部分,分别为93.6 MB.104 MB. 1.精简bin 运行桌面程序 ...

  3. Spring_Spring与DAO_Spring的事务管理

    一.Spring的事务管理 在Spring中通常可以通过以下三种方式来实现对事务的管理: 使用Spring的事务代理工厂管理事务 使用Spring的事务注解管理事务 使用AspectJ的AOP配置管理 ...

  4. Redis-概述

    Redis支持的类型: String,List,Map,Set,Sorted set Redis的持久化: 1.Redis DataBase (RDB): RDB是在某个时间点将数据写入一个临时文件, ...

  5. cf1060E. Sergey and Subway(树形dp)

    题意 题目链接 Sol 很套路的题 直接考虑每个边的贡献,最后再把奇数点的贡献算上 #include<bits/stdc++.h> #define Pair pair<int, in ...

  6. Drupal7配置简洁URL(Clear URL)

    参考:Apache Rewrite url重定向功能的简单配置 这两天折腾死了 首先说一下我的环境: Aache2.4.25-x64-vc14-r1;php-7.0.19-Win32-VC14-x64 ...

  7. MongoDB Limit/限制记录

    Limit() 方法 要限制 MongoDB 中的记录,需要使用 limit() 方法. limit() 方法接受一个数字型的参数,这是要显示的文档数. 语法: limit() 方法的基本语法如下 & ...

  8. 移动目标在三维GIS中的实现方法

    对于基于ArcGIS Runtime的应用程序,其实现方法比较简单,可以直接更新图形的Geometry属性,即可实现位置的移动: private void AddGraphics() { var gl ...

  9. 移动端H5开发 之 渲染引擎

    渲染引擎 浏览器渲染引擎,负责解析 HTML, CSS,javascript的DOM部分,如桌面浏览器一般手机端也有4个比较重要的渲染引擎 Gecko,Trident,WebKit,Blink . 黑 ...

  10. 如何在Ubuntu上安装gcc-6.3

    装显卡驱动推荐 gcc 6.3 版本,其实linux上多个版本的gcc是可以共存的,需要的的时候切换就好,参加之前的博客 https://www.cnblogs.com/jins-note/p/951 ...