Skip to content
This repository has been archived by the owner on Jun 17, 2022. It is now read-only.

Block info missing #193

Open
j4m3sb0mb opened this issue Feb 10, 2020 · 1 comment
Open

Block info missing #193

j4m3sb0mb opened this issue Feb 10, 2020 · 1 comment

Comments

@j4m3sb0mb
Copy link

Block informations as blockHeight, blockHash, prevBlockHash should be available to use pseudo-random functions in handlers

@j4m3sb0mb
Copy link
Author

I've written a small piece of code to have block number and prevHash in state:

const crypto = require('crypto')
const { stringify } = require('deterministic-json')
const BigNumber = require('bignumber.js');

module.exports = function () {
  return [
    {
      type: 'initializer',
      middleware: function (state) {
        state.block = {
          number: '0',
          prevHash: '',
        }
      }
    },
    {
      type: 'tx',
      middleware: function (state, transaction) {
        if (!state.block._tx_bytes) {
          state.block._tx_bytes = Buffer.from(stringify(transaction))
        } else {
          const curr__tx_bytes = Buffer.from(stringify(transaction))
          state.block._tx_bytes = Buffer.concat([state.block._tx_bytes, curr__tx_bytes])
        }
      }
    },
    {
      type: 'block',
      middleware: function (state) {
        const blockHash = crypto.createHash('sha256')
          .update(state.block.number)
          .update(state.block.prevHash)

        if (state.block._tx_bytes) {
          blockHash.update(state.block._tx_bytes)
          delete state.block._tx_bytes
        }

        state.block = {
          number: new BigNumber(state.block.number).plus(1).toFixed(),
          prevHash: blockHash.digest('hex'),
        }
      }
    }
  ]
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant