1. 程式人生 > >ethereumjs/ethereumjs-block-3-tests

ethereumjs/ethereumjs-block-3-tests

之前可以先了解一下另一個模組,看本部落格的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(32)) st.equal(header.uncleHash.toString('hex'), utils.SHA3_RLP_ARRAY_S) st.deepEqual(header.coinbase, utils.zeros(
20)) st.deepEqual(header.stateRoot, utils.zeros(32)) 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(256)) st.deepEqual(header.difficulty, Buffer.from
([])) st.deepEqual(header.number, utils.intToBuffer(1150000)) 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(32)) st.deepEqual(header.nonce, utils.zeros(8)) } 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[0].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[0].rlp))
    st.plan(2)
    testTransactionValidation(st, block)
  })

  t.test('should test transaction validation with empty transaction list', function (st) {
    var block = new Block()
    st.plan(2)
    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[2].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(2), '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(2), '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[2].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()