all files / ethereumjs-block/ index.js

42.86% Statements 48/112
13.89% Branches 5/36
16% Functions 4/25
42.86% Lines 48/112
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266             3159× 3159× 3159× 3159×   3159×           3159×     3159× 3159×     3159×       3159× 3159× 3159× 3159×               3159×         3159×                                                                                                                                                                                                                                                                                                                                                                                        
require('es6-shim')
const ethUtil = require('ethereumjs-util')
const Tx = require('ethereumjs-tx')
const Trie = require('merkle-patricia-tree')
const BN = ethUtil.BN
const rlp = ethUtil.rlp
const async = require('async')
const BlockHeader = require('./header')
const params = require('ethereum-common')
 
/**
 * Represents a block
 * @constructor
 * @param {Array} data raw data, deserialized
 */
var Block = module.exports = function (data) {
  this.transactions = []
  this.uncleHeaders = []
  this._inBlockChain = false
  this.txTrie = new Trie()
 
  Object.defineProperty(this, 'raw', {
    get: function () {
      return this.serialize(false)
    }
  })
 
  var rawTransactions, rawUncleHeaders
 
  // defaults
  Eif (!data) {
    data = [[], [], []]
  }
 
  Iif (Buffer.isBuffer(data)) {
    data = rlp.decode(data)
  }
 
  Eif (Array.isArray(data)) {
    this.header = new BlockHeader(data[0])
    rawTransactions = data[1]
    rawUncleHeaders = data[2]
  } else {
    this.header = new BlockHeader(data.header)
    rawTransactions = data.transactions
    rawUncleHeaders = data.uncleHeaders
  }
 
  // parse uncle headers
  for (var i = 0; i < rawUncleHeaders.length; i++) {
    this.uncleHeaders.push(new BlockHeader(rawUncleHeaders[i]))
  }
 
  // parse transactions
  for (i = 0; i < rawTransactions.length; i++) {
    this.transactions.push(new Tx(rawTransactions[i]))
  }
}
 
/**
 * Produces a hash the RLP of the block
 * @method hash
 */
Block.prototype.hash = function () {
  return this.header.hash()
}
 
/**
 * Determines if a given block is the genesis block
 * @method isGenisis
 * @return Boolean
 */
Block.prototype.isGenesis = function () {
  return this.header.isGenesis()
}
 
Block.prototype.setGenesisParams = function () {
  this.header.gasLimit = params.genesisGasLimit.v
  this.header.difficulty = params.genesisDifficulty.v
  this.header.extraData = params.genesisExtraData.v
  this.header.nonce = params.genesisNonce.v
  this.header.stateRoot = params.genesisStateRoot.v
}
 
/**
 * Produces a serialization of the block.
 * @method serialize
 * @param {Boolean} rlpEncode whether to rlp encode the block or not
 */
Block.prototype.serialize = function (rlpEncode) {
  var raw = [this.header.raw, [],
    []
  ]
 
  // rlpEnode defaults to true
  Eif (typeof rlpEncode === 'undefined') {
    rlpEncode = true
  }
 
  this.transactions.forEach(function (tx) {
    raw[1].push(tx.raw)
  })
 
  this.uncleHeaders.forEach(function (uncle) {
    raw[2].push(uncle.raw)
  })
 
  return rlpEncode ? rlp.encode(raw) : raw
}
 
/**
 * Generate transaction trie. The tx trie must be generated before the block can
 * be validated
 * @method genTxTrie
 * @param {Function} cb
 */
Block.prototype.genTxTrie = function (cb) {
  var i = 0
  var self = this
 
  async.eachSeries(this.transactions, function (tx, done) {
    self.txTrie.put(rlp.encode(i), tx.serialize(), done)
    i++
  }, cb)
}
 
/**
 * Validates the transaction trie
 * @method validateTransactionTrie
 * @return {Boolean}
 */
Block.prototype.validateTransactionsTrie = function () {
  var txT = this.header.transactionsTrie.toString('hex')
  if (this.transactions.length) {
    return txT === this.txTrie.root.toString('hex')
  } else {
    return txT === ethUtil.SHA3_RLP.toString('hex')
  }
}
 
/**
 * Validates the transactions
 * @method validateTransactions
 * @return {Boolean}
 */
Block.prototype.validateTransactions = function () {
  var validTxs = true
  this.transactions.forEach(function (tx) {
    validTxs &= tx.validate()
  })
  return validTxs
}
 
/**
 * Validates the block
 * @method validate
 * @param {BlockChain} blockChain the blockchain that this block wants to be part of
 * @param {Function} cb the callback which is given a `String` if the block is not valid
 */
Block.prototype.validate = function (blockChain, cb) {
  var self = this
 
  async.parallel([
    // validate uncles
    self.validateUncles.bind(self, blockChain),
    // validate block
    self.header.validate.bind(self.header, blockChain),
    // generate the transaction trie
    self.genTxTrie.bind(self)
  ], function (err) {
    if (!err) {
      if (!self.validateTransactionsTrie()) {
        err = 'invalid transaction true'
      }
 
      if (!self.validateTransactions()) {
        err = 'invalid transaction'
      }
 
      if (!self.validateUnclesHash()) {
        err = 'invild uncle hash'
      }
    }
 
    if (!err) {
      self.parentBlock = self.header.parentBlock
    }
 
    cb(err)
  })
}
 
Block.prototype.validateUnclesHash = function () {
  var raw = []
  this.uncleHeaders.forEach(function (uncle) {
    raw.push(uncle.raw)
  })
 
  raw = rlp.encode(raw)
  return ethUtil.sha3(raw).toString('hex') === this.header.uncleHash.toString('hex')
}
 
Block.prototype.validateUncles = function (blockChain, cb) {
  if (this.isGenesis()) {
    return cb()
  }
 
  var self = this
 
  if (self.uncleHeaders.length > 2) {
    return cb('too many uncle headers')
  }
 
  var uncleHashes = self.uncleHeaders.map(function (header) {
    return header.hash().toString('hex')
  })
 
  if (!((new Set(uncleHashes)).size === uncleHashes.length)) {
    return cb('dublicate unlces')
  }
 
  async.each(self.uncleHeaders, function (uncle, cb2) {
    var height = new BN(self.header.number)
    async.parallel([
      uncle.validate.bind(uncle, blockChain, height),
      // check to make sure the uncle is not already in the blockchain
      function (cb3) {
        blockChain.getDetails(uncle.hash(), function (err, blockInfo) {
          // TODO: remove uncles from BC
          if (blockInfo && blockInfo.isUncle) {
            cb3(err || 'uncle already included')
          } else {
            cb3()
          }
        })
      }
    ], cb2)
  }, cb)
}
 
/**
 * Converts the block toJSON
 * @method toJSON
 * @param {Bool} array whether to create a object or an array
 */
Block.prototype.toJSON = function (labeled) {
  if (labeled) {
    var obj = {
      header: this.header.toJSON(true),
      transactions: [],
      uncleHeaders: []
    }
 
    this.transactions.forEach(function (tx) {
      obj.transactions.push(tx.toJSON(labeled))
    })
 
    this.uncleHeaders.forEach(function (uh) {
      obj.uncleHeaders.push(uh.toJSON())
    })
    return obj
  } else {
    return ethUtil.baToJSON(this.raw)
  }
}