<commit_before>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global slice, splice, max, fail, Stream */

var codeLengthOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];

var distanceCodes = [];
var distanceExtraBits = [];
for (var i = 0, j = 0, code = 1; i < 30; ++i) {
  distanceCodes[i] = code;
  code += 1 << (distanceExtraBits[i] = ~~((j += (i > 2 ? 1 : 0)) / 2));
}

var bitLengths = [];
for (var i = 0; i < 32; ++i)
  bitLengths[i] = 5;
var fixedDistanceTable = makeHuffmanTable(bitLengths);

var lengthCodes = [];
var lengthExtraBits = [];
for (var i = 0, j = 0, code = 3; i < 29; ++i) {
  lengthCodes[i] = code - (i == 28 ? 1 : 0);
  code += 1 << (lengthExtraBits[i] = ~~(((j += (i > 4 ? 1 : 0)) / 4) % 6));
}

for (var i = 0; i < 288; ++i)
  bitLengths[i] = i < 144 || i > 279 ? 8 : (i < 256 ? 9 : 7);
var fixedLiteralTable = makeHuffmanTable(bitLengths);

function makeHuffmanTable(bitLengths) {
  var maxBits = max.apply(null, bitLengths);
  var numLengths = bitLengths.length;
  var size = 1 << maxBits;
  var codes = new Uint32Array(size);
  for (var code = 0, len = 1, skip = 2; len <= maxBits; code <<= 1, ++len, skip <<= 1) {
    for (var val = 0; val < numLengths; ++val) {
      if (bitLengths[val] === len) {
        var lsb = 0;
        for (var i = 0; i < len; ++i)
          lsb = (lsb * 2) + ((code >> i) & 1);
        for (var i = lsb; i < size; i += skip)
          codes[i] = (len << 16) | val;
        ++code;
      }
    }
  }
  return { codes: codes, maxBits: maxBits };
}

function verifyDeflateHeader(bytes) {
  var header = (bytes[0] << 8) | bytes[1];
  assert((header & 0x0f00) === 0x0800, 'unknown compression method', 'inflate');
  assert((header % 31) === 0, 'bad FCHECK', 'inflate');
  assert(!(header & 0x20), 'FDICT bit set', 'inflate');
}

function createInflatedStream(bytes, outputLength) {
  verifyDeflateHeader(bytes);
  var stream = new Stream(bytes, 2);
  var output = {
    data: new Uint8Array(outputLength),
    available: 0,
    completed: false
  };
  var state = { header: null, distanceTable: null, literalTable: null,
    sym: null, len: null, sym2: null };
  do {
    inflateBlock(stream, output, state);
  } while (!output.completed && stream.pos < stream.end);
  return new Stream(output.data, 0, output.available);
}

var InflateNoDataError = {};

function inflateBlock(stream, output, state) {
  var header = state.header !== null ? state.header :
    (state.header = readBits(stream.bytes, stream, 3));
  switch (header >> 1) {
  case 0:
    stream.align();
    var pos = stream.pos;
    if (stream.end - pos < 4) {
      throw InflateNoDataError;
    }
    var len = stream.getUint16(pos, true);
    var nlen = stream.getUint16(pos + 2, true);
    assert((~nlen & 0xffff) === len, 'bad uncompressed block length', 'inflate');
    if (stream.end - pos < 4 + len) {
      throw InflateNoDataError;
    }
    var begin = pos + 4;
    var end = stream.pos = begin + len;
    var sbytes = stream.bytes, dbytes = output.data;
    splice.apply(dbytes, [output.available, len].concat(slice.call(sbytes, begin, end)));
    output.available += len;
    break;
  case 1:
    inflate(stream, output, fixedLiteralTable, fixedDistanceTable, state);
    break;
  case 2:
    var distanceTable, literalTable;
    if (state.distanceTable !== null) {
      distanceTable = state.distanceTable;
      literalTable = state.literalTable;
    } else {
      var sbytes = stream.bytes;
      var savedBufferPos = stream.pos;
      var savedBitBuffer = stream.bitBuffer;
      var savedBitLength = stream.bitLength;
      var bitLengths = [];
      var numLiteralCodes, numDistanceCodes;
      try  {
        numLiteralCodes = readBits(sbytes, stream, 5) + 257;
        numDistanceCodes = readBits(sbytes, stream, 5) + 1;
        var numCodes = numLiteralCodes + numDistanceCodes;
        var numLengthCodes = readBits(sbytes, stream, 4) + 4;
        for (var i = 0; i < 19; ++i)
          bitLengths[codeLengthOrder[i]] = i < numLengthCodes ? readBits(sbytes, stream, 3) : 0;
        var codeLengthTable = makeHuffmanTable(bitLengths);
        bitLengths = [];
        var i = 0;
        var prev = 0;
        while (i < numCodes) {
          var j = 1;
          var sym = readCode(sbytes, stream, codeLengthTable);
          switch(sym){
          case 16:
            j = readBits(sbytes, stream, 2) + 3;
            sym = prev;
            break;
          case 17:
            j = readBits(sbytes, stream, 3) + 3;
            sym = 0;
            break;
          case 18:
            j = readBits(sbytes, stream, 7) + 11;
            sym = 0;
            break;
          default:
            prev = sym;
          }
          while (j--)
            bitLengths[i++] = sym;
        }
      } catch (e) {
        stream.pos = savedBufferPos;
        stream.bitBuffer = savedBitBuffer;
        stream.bitLength = savedBitLength;
        throw e;
      }
      distanceTable = state.distanceTable = makeHuffmanTable(bitLengths.splice(numLiteralCodes, numDistanceCodes));
      literalTable = state.literalTable = makeHuffmanTable(bitLengths);
    }
    inflate(stream, output, literalTable, distanceTable, state);
    state.distanceTable = null;
    state.literalTable = null;
    break;
  default:
     fail('unknown block type', 'inflate');
  }
  state.header = null;
  output.completed = !!(header & 1);
}
function readBits(bytes, stream, size) {
  var bitBuffer = stream.bitBuffer;
  var bitLength = stream.bitLength;
  if (size > bitLength) {
    var pos = stream.pos;
    var end = stream.end;
    do {
      if (pos >= end) {
        stream.pos = pos;
        stream.bitBuffer = bitBuffer;
        stream.bitLength = bitLength;
        throw InflateNoDataError;
      }
      bitBuffer |= bytes[pos++] << bitLength;
      bitLength += 8;
    } while (size > bitLength);
    stream.pos = pos;
  }
  stream.bitBuffer = bitBuffer >>> size;
  stream.bitLength = bitLength - size;
  return bitBuffer & ((1 << size) - 1);
}
function inflate(stream, output, literalTable, distanceTable, state) {
  var pos = output.available;
  var dbytes = output.data;
  var sbytes = stream.bytes;
  var sym = state.sym !== null ? state.sym :
    readCode(sbytes, stream, literalTable);
  while (sym !== 256) {
    if (sym < 256) {
      dbytes[pos++] = sym;
    } else {
      state.sym = sym;
      sym -= 257;
      var len = state.len !== null ? state.len :
        (state.len = lengthCodes[sym] + readBits(sbytes, stream, lengthExtraBits[sym]));
      var sym2 = state.sym2 !== null ? state.sym2 :
        (state.sym2 = readCode(sbytes, stream, distanceTable));
      var distance = distanceCodes[sym2] + readBits(sbytes, stream, distanceExtraBits[sym2]);
      var i = pos - distance;
      while (len--)
        dbytes[pos++] = dbytes[i++];
      state.sym2 = null;
      state.len = null;
      state.sym = null;
    }
    output.available = pos;
    sym = readCode(sbytes, stream, literalTable);
  }
}
function readCode(bytes, stream, codeTable) {
  var bitBuffer = stream.bitBuffer;
  var bitLength = stream.bitLength;
  var maxBits = codeTable.maxBits;
  if (maxBits > bitLength) {
    var pos = stream.pos;
    var end = stream.end;
    do {
      if (pos >= end) {
        stream.pos = pos;
        stream.bitBuffer = bitBuffer;
        stream.bitLength = bitLength;
        throw InflateNoDataError;
      }
      bitBuffer |= bytes[pos++] << bitLength;
      bitLength += 8;
    } while (maxBits > bitLength);
    stream.pos = pos;
  }
  var code = codeTable.codes[bitBuffer & ((1 << maxBits) - 1)];
  var len = code >> 16;
  assert(len, 'bad encoding', 'inflate');
  stream.bitBuffer = bitBuffer >>> len;
  stream.bitLength = bitLength - len;
  return code & 0xffff;
}
<commit_msg>Removes splice/slice usage for typed arrays<commit_after>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global fail, Stream */

var codeLengthOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];

var distanceCodes = [];
var distanceExtraBits = [];
for (var i = 0, j = 0, code = 1; i < 30; ++i) {
  distanceCodes[i] = code;
  code += 1 << (distanceExtraBits[i] = ~~((j += (i > 2 ? 1 : 0)) / 2));
}

var bitLengths = [];
for (var i = 0; i < 32; ++i)
  bitLengths[i] = 5;
var fixedDistanceTable = makeHuffmanTable(bitLengths);

var lengthCodes = [];
var lengthExtraBits = [];
for (var i = 0, j = 0, code = 3; i < 29; ++i) {
  lengthCodes[i] = code - (i == 28 ? 1 : 0);
  code += 1 << (lengthExtraBits[i] = ~~(((j += (i > 4 ? 1 : 0)) / 4) % 6));
}

for (var i = 0; i < 288; ++i)
  bitLengths[i] = i < 144 || i > 279 ? 8 : (i < 256 ? 9 : 7);
var fixedLiteralTable = makeHuffmanTable(bitLengths);

function makeHuffmanTable(bitLengths) {
  var maxBits = Math.max.apply(null, bitLengths);
  var numLengths = bitLengths.length;
  var size = 1 << maxBits;
  var codes = new Uint32Array(size);
  for (var code = 0, len = 1, skip = 2; len <= maxBits; code <<= 1, ++len, skip <<= 1) {
    for (var val = 0; val < numLengths; ++val) {
      if (bitLengths[val] === len) {
        var lsb = 0;
        for (var i = 0; i < len; ++i)
          lsb = (lsb * 2) + ((code >> i) & 1);
        for (var i = lsb; i < size; i += skip)
          codes[i] = (len << 16) | val;
        ++code;
      }
    }
  }
  return { codes: codes, maxBits: maxBits };
}

function verifyDeflateHeader(bytes) {
  var header = (bytes[0] << 8) | bytes[1];
  assert((header & 0x0f00) === 0x0800, 'unknown compression method', 'inflate');
  assert((header % 31) === 0, 'bad FCHECK', 'inflate');
  assert(!(header & 0x20), 'FDICT bit set', 'inflate');
}

function createInflatedStream(bytes, outputLength) {
  verifyDeflateHeader(bytes);
  var stream = new Stream(bytes, 2);
  var output = {
    data: new Uint8Array(outputLength),
    available: 0,
    completed: false
  };
  var state = { header: null, distanceTable: null, literalTable: null,
    sym: null, len: null, sym2: null };
  do {
    inflateBlock(stream, output, state);
  } while (!output.completed && stream.pos < stream.end);
  return new Stream(output.data, 0, output.available);
}

var InflateNoDataError = {};

function inflateBlock(stream, output, state) {
  var header = state.header !== null ? state.header :
    (state.header = readBits(stream.bytes, stream, 3));
  switch (header >> 1) {
  case 0:
    stream.align();
    var pos = stream.pos;
    if (stream.end - pos < 4) {
      throw InflateNoDataError;
    }
    var len = stream.getUint16(pos, true);
    var nlen = stream.getUint16(pos + 2, true);
    assert((~nlen & 0xffff) === len, 'bad uncompressed block length', 'inflate');
    if (stream.end - pos < 4 + len) {
      throw InflateNoDataError;
    }
    var begin = pos + 4;
    var end = stream.pos = begin + len;
    var sbytes = stream.bytes, dbytes = output.data;
    dbytes.set(sbytes.subarray(begin, end), output.available);
    output.available += len;
    break;
  case 1:
    inflate(stream, output, fixedLiteralTable, fixedDistanceTable, state);
    break;
  case 2:
    var distanceTable, literalTable;
    if (state.distanceTable !== null) {
      distanceTable = state.distanceTable;
      literalTable = state.literalTable;
    } else {
      var sbytes = stream.bytes;
      var savedBufferPos = stream.pos;
      var savedBitBuffer = stream.bitBuffer;
      var savedBitLength = stream.bitLength;
      var bitLengths = [];
      var numLiteralCodes, numDistanceCodes;
      try  {
        numLiteralCodes = readBits(sbytes, stream, 5) + 257;
        numDistanceCodes = readBits(sbytes, stream, 5) + 1;
        var numCodes = numLiteralCodes + numDistanceCodes;
        var numLengthCodes = readBits(sbytes, stream, 4) + 4;
        for (var i = 0; i < 19; ++i)
          bitLengths[codeLengthOrder[i]] = i < numLengthCodes ? readBits(sbytes, stream, 3) : 0;
        var codeLengthTable = makeHuffmanTable(bitLengths);
        bitLengths = [];
        var i = 0;
        var prev = 0;
        while (i < numCodes) {
          var j = 1;
          var sym = readCode(sbytes, stream, codeLengthTable);
          switch(sym){
          case 16:
            j = readBits(sbytes, stream, 2) + 3;
            sym = prev;
            break;
          case 17:
            j = readBits(sbytes, stream, 3) + 3;
            sym = 0;
            break;
          case 18:
            j = readBits(sbytes, stream, 7) + 11;
            sym = 0;
            break;
          default:
            prev = sym;
          }
          while (j--)
            bitLengths[i++] = sym;
        }
      } catch (e) {
        stream.pos = savedBufferPos;
        stream.bitBuffer = savedBitBuffer;
        stream.bitLength = savedBitLength;
        throw e;
      }
      distanceTable = state.distanceTable = makeHuffmanTable(bitLengths.splice(numLiteralCodes, numDistanceCodes));
      literalTable = state.literalTable = makeHuffmanTable(bitLengths);
    }
    inflate(stream, output, literalTable, distanceTable, state);
    state.distanceTable = null;
    state.literalTable = null;
    break;
  default:
     fail('unknown block type', 'inflate');
  }
  state.header = null;
  output.completed = !!(header & 1);
}
function readBits(bytes, stream, size) {
  var bitBuffer = stream.bitBuffer;
  var bitLength = stream.bitLength;
  if (size > bitLength) {
    var pos = stream.pos;
    var end = stream.end;
    do {
      if (pos >= end) {
        stream.pos = pos;
        stream.bitBuffer = bitBuffer;
        stream.bitLength = bitLength;
        throw InflateNoDataError;
      }
      bitBuffer |= bytes[pos++] << bitLength;
      bitLength += 8;
    } while (size > bitLength);
    stream.pos = pos;
  }
  stream.bitBuffer = bitBuffer >>> size;
  stream.bitLength = bitLength - size;
  return bitBuffer & ((1 << size) - 1);
}
function inflate(stream, output, literalTable, distanceTable, state) {
  var pos = output.available;
  var dbytes = output.data;
  var sbytes = stream.bytes;
  var sym = state.sym !== null ? state.sym :
    readCode(sbytes, stream, literalTable);
  while (sym !== 256) {
    if (sym < 256) {
      dbytes[pos++] = sym;
    } else {
      state.sym = sym;
      sym -= 257;
      var len = state.len !== null ? state.len :
        (state.len = lengthCodes[sym] + readBits(sbytes, stream, lengthExtraBits[sym]));
      var sym2 = state.sym2 !== null ? state.sym2 :
        (state.sym2 = readCode(sbytes, stream, distanceTable));
      var distance = distanceCodes[sym2] + readBits(sbytes, stream, distanceExtraBits[sym2]);
      var i = pos - distance;
      while (len--)
        dbytes[pos++] = dbytes[i++];
      state.sym2 = null;
      state.len = null;
      state.sym = null;
    }
    output.available = pos;
    sym = readCode(sbytes, stream, literalTable);
  }
}
function readCode(bytes, stream, codeTable) {
  var bitBuffer = stream.bitBuffer;
  var bitLength = stream.bitLength;
  var maxBits = codeTable.maxBits;
  if (maxBits > bitLength) {
    var pos = stream.pos;
    var end = stream.end;
    do {
      if (pos >= end) {
        stream.pos = pos;
        stream.bitBuffer = bitBuffer;
        stream.bitLength = bitLength;
        throw InflateNoDataError;
      }
      bitBuffer |= bytes[pos++] << bitLength;
      bitLength += 8;
    } while (maxBits > bitLength);
    stream.pos = pos;
  }
  var code = codeTable.codes[bitBuffer & ((1 << maxBits) - 1)];
  var len = code >> 16;
  assert(len, 'bad encoding', 'inflate');
  stream.bitBuffer = bitBuffer >>> len;
  stream.bitLength = bitLength - len;
  return code & 0xffff;
}
<|endoftext|>


<commit_before>var assert = require('assert')
var bufferutils = require('./bufferutils')
var crypto = require('./crypto')
var typeForce = require('typeforce')
var opcodes = require('./opcodes')

var Script = require('./script')

function Transaction () {
  this.blockPos = null
  this.version = 1
  this.locktime = 0
  this.ins = []
  this.outs = []
}

Transaction.DEFAULT_SEQUENCE = 0xffffffff
Transaction.SIGHASH_ALL = 0x01
Transaction.SIGHASH_NONE = 0x02
Transaction.SIGHASH_SINGLE = 0x03
Transaction.SIGHASH_ANYONECANPAY = 0x80

Transaction.fromBuffer = function (buffer, __disableAssert) {
  var offset = 0
  function readSlice (n) {
    offset += n
    return buffer.slice(offset - n, offset)
  }

  function readUInt32 () {
    var i = buffer.readUInt32LE(offset)
    offset += 4
    return i
  }

  function readUInt64 () {
    var i = bufferutils.readUInt64LE(buffer, offset)
    offset += 8
    return i
  }

  function readVarInt () {
    var vi = bufferutils.readVarInt(buffer, offset)
    offset += vi.size
    return vi.number
  }

  function readScript () {
    return Script.fromBuffer(readSlice(readVarInt()))
  }

  function readGenerationScript () {
    return new Script(readSlice(readVarInt()), [])
  }

  var tx = new Transaction()
  tx.version = readUInt32()

  var vinLen = readVarInt()
  for (var i = 0; i < vinLen; ++i) {
    var hash = readSlice(32)

    if (Transaction.isCoinbaseHash(hash)) {
      tx.ins.push({
        hash: hash,
        index: readUInt32(),
        script: readGenerationScript(),
        sequence: readUInt32()
      })
    } else {
      tx.ins.push({
        hash: hash,
        index: readUInt32(),
        script: readScript(),
        sequence: readUInt32()
      })
    }
  }

  var voutLen = readVarInt()
  for (i = 0; i < voutLen; ++i) {
    tx.outs.push({
      value: readUInt64(),
      script: readScript()
    })
  }

  tx.locktime = readUInt32()

  if (!__disableAssert) {
    assert.equal(offset, buffer.length, 'Transaction has unexpected data')
  }

  return tx
}

Transaction.fromHex = function (hex) {
  return Transaction.fromBuffer(new Buffer(hex, 'hex'))
}

Transaction.isCoinbaseHash = function (buffer) {
  return Array.prototype.every.call(buffer, function (x) {
    return x === 0
  })
}

Transaction.prototype.addInput = function (hash, index, sequence, script) {
  if (sequence === undefined || sequence === null) {
    sequence = Transaction.DEFAULT_SEQUENCE
  }

  script = script || Script.EMPTY

  typeForce('Buffer', hash)
  typeForce('Number', index)
  typeForce('Number', sequence)
  typeForce('Script', script)

  assert.equal(hash.length, 32, 'Expected hash length of 32, got ' + hash.length)

  // Add the input and return the input's index
  return (this.ins.push({
    hash: hash,
    index: index,
    script: script,
    sequence: sequence
  }) - 1)
}

Transaction.prototype.addOutput = function (scriptPubKey, value) {
  typeForce('Script', scriptPubKey)
  typeForce('Number', value)

  // Add the output and return the output's index
  return (this.outs.push({
    script: scriptPubKey,
    value: value
  }) - 1)
}

Transaction.prototype.byteLength = function () {
  function scriptSize (script) {
    var length = script.buffer.length

    return bufferutils.varIntSize(length) + length
  }

  return (
    8 +
    bufferutils.varIntSize(this.ins.length) +
    bufferutils.varIntSize(this.outs.length) +
    this.ins.reduce(function (sum, input) { return sum + 40 + scriptSize(input.script) }, 0) +
    this.outs.reduce(function (sum, output) { return sum + 8 + scriptSize(output.script) }, 0)
  )
}

Transaction.prototype.clone = function () {
  var newTx = new Transaction()
  newTx.version = this.version
  newTx.locktime = this.locktime

  newTx.ins = this.ins.map(function (txIn) {
    return {
      hash: txIn.hash,
      index: txIn.index,
      script: txIn.script,
      sequence: txIn.sequence
    }
  })

  newTx.outs = this.outs.map(function (txOut) {
    return {
      script: txOut.script,
      value: txOut.value
    }
  })

  return newTx
}

var one = new Buffer('0000000000000000000000000000000000000000000000000000000000000001', 'hex')

/**
 * Hash transaction for signing a specific input.
 *
 * Bitcoin uses a different hash for each signed transaction input.
 * This method copies the transaction, makes the necessary changes based on the
 * hashType, and then hashes the result.
 * This hash can then be used to sign the provided transaction input.
 */
Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
  typeForce('Number', inIndex)
  typeForce('Script', prevOutScript)
  typeForce('Number', hashType)

  assert(inIndex >= 0, 'Invalid vin index')

  // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
  if (inIndex >= this.ins.length) return one

  var txTmp = this.clone()

  // in case concatenating two scripts ends up with two codeseparators,
  // or an extra one at the end, this prevents all those possible incompatibilities.
  var hashScript = prevOutScript.without(opcodes.OP_CODESEPARATOR)
  var i

  // blank out other inputs' signatures
  txTmp.ins.forEach(function (input) { input.script = Script.EMPTY })
  txTmp.ins[inIndex].script = hashScript

  // blank out some of the inputs
  if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
    // wildcard payee
    txTmp.outs = []

    // let the others update at will
    txTmp.ins.forEach(function (input, i) {
      if (i !== inIndex) {
        input.sequence = 0
      }
    })

  } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
    var nOut = inIndex

    // only lock-in the txOut payee at same index as txIn
    // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
    if (nOut >= this.outs.length) return one

    txTmp.outs = txTmp.outs.slice(0, nOut + 1)

    // blank all other outputs (clear scriptPubKey, value === -1)
    var stubOut = {
      script: Script.EMPTY,
      valueBuffer: new Buffer('ffffffffffffffff', 'hex')
    }

    for (i = 0; i < nOut; i++) {
      txTmp.outs[i] = stubOut
    }

    // let the others update at will
    txTmp.ins.forEach(function (input, i) {
      if (i !== inIndex) {
        input.sequence = 0
      }
    })
  }

  // blank out other inputs completely, not recommended for open transactions
  if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
    txTmp.ins[0] = txTmp.ins[inIndex]
    txTmp.ins = txTmp.ins.slice(0, 1)
  }

  // serialize and hash
  var buffer = new Buffer(txTmp.byteLength() + 4)
  buffer.writeInt32LE(hashType, buffer.length - 4)
  txTmp.toBuffer().copy(buffer, 0)

  return crypto.hash256(buffer)
}

Transaction.prototype.getHash = function () {
  return crypto.hash256(this.toBuffer())
}

Transaction.prototype.getId = function () {
  // TxHash is little-endian, we need big-endian
  return bufferutils.reverse(this.getHash()).toString('hex')
}

Transaction.prototype.toBuffer = function () {
  var buffer = new Buffer(this.byteLength())

  var offset = 0
  function writeSlice (slice) {
    slice.copy(buffer, offset)
    offset += slice.length
  }

  function writeUInt32 (i) {
    buffer.writeUInt32LE(i, offset)
    offset += 4
  }

  function writeUInt64 (i) {
    bufferutils.writeUInt64LE(buffer, i, offset)
    offset += 8
  }

  function writeVarInt (i) {
    var n = bufferutils.writeVarInt(buffer, i, offset)
    offset += n
  }

  writeUInt32(this.version)
  writeVarInt(this.ins.length)

  this.ins.forEach(function (txIn) {
    writeSlice(txIn.hash)
    writeUInt32(txIn.index)
    writeVarInt(txIn.script.buffer.length)
    writeSlice(txIn.script.buffer)
    writeUInt32(txIn.sequence)
  })

  writeVarInt(this.outs.length)
  this.outs.forEach(function (txOut) {
    if (!txOut.valueBuffer) {
      writeUInt64(txOut.value)
    } else {
      writeSlice(txOut.valueBuffer)
    }

    writeVarInt(txOut.script.buffer.length)
    writeSlice(txOut.script.buffer)
  })

  writeUInt32(this.locktime)

  return buffer
}

Transaction.prototype.toHex = function () {
  return this.toBuffer().toString('hex')
}

Transaction.prototype.setInputScript = function (index, script) {
  typeForce('Number', index)
  typeForce('Script', script)

  this.ins[index].script = script
}

module.exports = Transaction
<commit_msg>Transaction Indexer Updates<commit_after>var assert = require('assert')
var bufferutils = require('./bufferutils')
var crypto = require('./crypto')
var typeForce = require('typeforce')
var opcodes = require('./opcodes')

var Script = require('./script')

function Transaction () {
  this.blockPos = null
  this.version = 1
  this.locktime = 0
  this.ins = []
  this.outs = []
}

Transaction.DEFAULT_SEQUENCE = 0xffffffff
Transaction.SIGHASH_ALL = 0x01
Transaction.SIGHASH_NONE = 0x02
Transaction.SIGHASH_SINGLE = 0x03
Transaction.SIGHASH_ANYONECANPAY = 0x80

Transaction.fromBuffer = function (buffer, __disableAssert) {
  var offset = 0
  function readSlice (n) {
    offset += n
    return buffer.slice(offset - n, offset)
  }

  function readUInt32 () {
    var i = buffer.readUInt32LE(offset)
    offset += 4
    return i
  }

  function readUInt64 () {
    var i = bufferutils.readUInt64LE(buffer, offset)
    offset += 8
    return i
  }

  function readVarInt () {
    var vi = bufferutils.readVarInt(buffer, offset)
    offset += vi.size
    return vi.number
  }

  function readScript () {
    return Script.fromBuffer(readSlice(readVarInt()))
  }

  function readGenerationScript () {
    return new Script(readSlice(readVarInt()), [])
  }

  var tx = new Transaction()
  tx.version = readUInt32()

  var vinLen = readVarInt()
  for (var i = 0; i < vinLen; ++i) {
    var hash = readSlice(32)

    if (Transaction.isCoinbaseHash(hash)) {
      tx.ins.push({
        hash: hash,
        index: readUInt32(),
        script: readGenerationScript(),
        sequence: readUInt32(),
        n: i
      })
    } else {
      tx.ins.push({
        hash: hash,
        index: readUInt32(),
        script: readScript(),
        sequence: readUInt32(),
        n: i
      })
    }
  }

  var voutLen = readVarInt()
  for (i = 0; i < voutLen; ++i) {
    tx.outs.push({
      value: readUInt64(),
      script: readScript(),
      n: i
    })
  }

  tx.locktime = readUInt32()

  if (!__disableAssert) {
    assert.equal(offset, buffer.length, 'Transaction has unexpected data')
  }

  return tx
}

Transaction.fromHex = function (hex) {
  return Transaction.fromBuffer(new Buffer(hex, 'hex'))
}

Transaction.isCoinbaseHash = function (buffer) {
  return Array.prototype.every.call(buffer, function (x) {
    return x === 0
  })
}

Transaction.prototype.addInput = function (hash, index, sequence, script) {
  if (sequence === undefined || sequence === null) {
    sequence = Transaction.DEFAULT_SEQUENCE
  }

  script = script || Script.EMPTY

  typeForce('Buffer', hash)
  typeForce('Number', index)
  typeForce('Number', sequence)
  typeForce('Script', script)

  assert.equal(hash.length, 32, 'Expected hash length of 32, got ' + hash.length)

  // Add the input and return the input's index
  return (this.ins.push({
    hash: hash,
    index: index,
    script: script,
    sequence: sequence
  }) - 1)
}

Transaction.prototype.addOutput = function (scriptPubKey, value) {
  typeForce('Script', scriptPubKey)
  typeForce('Number', value)

  // Add the output and return the output's index
  return (this.outs.push({
    script: scriptPubKey,
    value: value
  }) - 1)
}

Transaction.prototype.byteLength = function () {
  function scriptSize (script) {
    var length = script.buffer.length

    return bufferutils.varIntSize(length) + length
  }

  return (
    8 +
    bufferutils.varIntSize(this.ins.length) +
    bufferutils.varIntSize(this.outs.length) +
    this.ins.reduce(function (sum, input) { return sum + 40 + scriptSize(input.script) }, 0) +
    this.outs.reduce(function (sum, output) { return sum + 8 + scriptSize(output.script) }, 0)
  )
}

Transaction.prototype.clone = function () {
  var newTx = new Transaction()
  newTx.version = this.version
  newTx.locktime = this.locktime

  newTx.ins = this.ins.map(function (txIn) {
    return {
      hash: txIn.hash,
      index: txIn.index,
      script: txIn.script,
      sequence: txIn.sequence
    }
  })

  newTx.outs = this.outs.map(function (txOut) {
    return {
      script: txOut.script,
      value: txOut.value
    }
  })

  return newTx
}

var one = new Buffer('0000000000000000000000000000000000000000000000000000000000000001', 'hex')

/**
 * Hash transaction for signing a specific input.
 *
 * Bitcoin uses a different hash for each signed transaction input.
 * This method copies the transaction, makes the necessary changes based on the
 * hashType, and then hashes the result.
 * This hash can then be used to sign the provided transaction input.
 */
Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
  typeForce('Number', inIndex)
  typeForce('Script', prevOutScript)
  typeForce('Number', hashType)

  assert(inIndex >= 0, 'Invalid vin index')

  // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
  if (inIndex >= this.ins.length) return one

  var txTmp = this.clone()

  // in case concatenating two scripts ends up with two codeseparators,
  // or an extra one at the end, this prevents all those possible incompatibilities.
  var hashScript = prevOutScript.without(opcodes.OP_CODESEPARATOR)
  var i

  // blank out other inputs' signatures
  txTmp.ins.forEach(function (input) { input.script = Script.EMPTY })
  txTmp.ins[inIndex].script = hashScript

  // blank out some of the inputs
  if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
    // wildcard payee
    txTmp.outs = []

    // let the others update at will
    txTmp.ins.forEach(function (input, i) {
      if (i !== inIndex) {
        input.sequence = 0
      }
    })

  } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
    var nOut = inIndex

    // only lock-in the txOut payee at same index as txIn
    // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
    if (nOut >= this.outs.length) return one

    txTmp.outs = txTmp.outs.slice(0, nOut + 1)

    // blank all other outputs (clear scriptPubKey, value === -1)
    var stubOut = {
      script: Script.EMPTY,
      valueBuffer: new Buffer('ffffffffffffffff', 'hex')
    }

    for (i = 0; i < nOut; i++) {
      txTmp.outs[i] = stubOut
    }

    // let the others update at will
    txTmp.ins.forEach(function (input, i) {
      if (i !== inIndex) {
        input.sequence = 0
      }
    })
  }

  // blank out other inputs completely, not recommended for open transactions
  if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
    txTmp.ins[0] = txTmp.ins[inIndex]
    txTmp.ins = txTmp.ins.slice(0, 1)
  }

  // serialize and hash
  var buffer = new Buffer(txTmp.byteLength() + 4)
  buffer.writeInt32LE(hashType, buffer.length - 4)
  txTmp.toBuffer().copy(buffer, 0)

  return crypto.hash256(buffer)
}

Transaction.prototype.getHash = function () {
  return crypto.hash256(this.toBuffer())
}

Transaction.prototype.getId = function () {
  // TxHash is little-endian, we need big-endian
  return bufferutils.reverse(this.getHash()).toString('hex')
}

Transaction.prototype.toBuffer = function () {
  var buffer = new Buffer(this.byteLength())

  var offset = 0
  function writeSlice (slice) {
    slice.copy(buffer, offset)
    offset += slice.length
  }

  function writeUInt32 (i) {
    buffer.writeUInt32LE(i, offset)
    offset += 4
  }

  function writeUInt64 (i) {
    bufferutils.writeUInt64LE(buffer, i, offset)
    offset += 8
  }

  function writeVarInt (i) {
    var n = bufferutils.writeVarInt(buffer, i, offset)
    offset += n
  }

  writeUInt32(this.version)
  writeVarInt(this.ins.length)

  this.ins.forEach(function (txIn) {
    writeSlice(txIn.hash)
    writeUInt32(txIn.index)
    writeVarInt(txIn.script.buffer.length)
    writeSlice(txIn.script.buffer)
    writeUInt32(txIn.sequence)
  })

  writeVarInt(this.outs.length)
  this.outs.forEach(function (txOut) {
    if (!txOut.valueBuffer) {
      writeUInt64(txOut.value)
    } else {
      writeSlice(txOut.valueBuffer)
    }

    writeVarInt(txOut.script.buffer.length)
    writeSlice(txOut.script.buffer)
  })

  writeUInt32(this.locktime)

  return buffer
}

Transaction.prototype.toHex = function () {
  return this.toBuffer().toString('hex')
}

Transaction.prototype.setInputScript = function (index, script) {
  typeForce('Number', index)
  typeForce('Script', script)

  this.ins[index].script = script
}

module.exports = Transaction
<|endoftext|>


<commit_before>define(['clamp', 'flockn/constants/color'], function(clamp, colorConstants) {
  var Color = function(r, g, b, a) {
    this.r = r || 0;
    this.g = g || 0;
    this.b = b || 0;
    this.a = a || 1;
  };

  Color.prototype.lighten = function(factor) {
    factor = clamp(factor, 0, 1);

    this.r = clamp(this.r + (factor * 255) | 0, 0, 255);
    this.g = clamp(this.g + (factor * 255) | 0, 0, 255);
    this.b = clamp(this.b + (factor * 255) | 0, 0, 255);
  };

  Color.prototype.darken = function(factor) {
    factor = clamp(factor, 0, 1);

    this.r = clamp(this.r - (factor * 255) | 0, 0, 255);
    this.g = clamp(this.g - (factor * 255) | 0, 0, 255);
    this.b = clamp(this.b - (factor * 255) | 0, 0, 255);
  };

  Color.prototype.fadeIn = function(factor) {
    factor = clamp(factor, 0, 1);

    this.a = this.a + this.a * factor;
    if (this.a > 1) {
      this.a = 1;
    }
  };

  Color.prototype.fadeOut = function(factor) {
    factor = clamp(factor, 0, 1);

    this.a = this.a - this.a * factor;
    if (this.a < 0) {
      this.a = 0;
    }
  };

  Color.prototype.toString = function() {
    if (a < 1) {
      return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
    } else {
      return 'rgb(' + this.r + ',' + this.g + ',' + this.b + ')';
    }
  };

  for (var colorName in colorConstants) {
    var colorValue = colorConstants[colorName];
    Color[colorName] = new Color(colorValue.r, colorValue.g, colorValue.b, colorValue.a);
  }

  return Color;
});<commit_msg>Fixes alpha part<commit_after>define(['clamp', 'flockn/constants/color'], function(clamp, colorConstants) {
  var Color = function(r, g, b, a) {
    this.r = r || 0;
    this.g = g || 0;
    this.b = b || 0;
    this.a = a || 1;
  };

  Color.prototype.lighten = function(factor) {
    factor = clamp(factor, 0, 1);

    this.r = clamp(this.r + (factor * 255) | 0, 0, 255);
    this.g = clamp(this.g + (factor * 255) | 0, 0, 255);
    this.b = clamp(this.b + (factor * 255) | 0, 0, 255);
  };

  Color.prototype.darken = function(factor) {
    factor = clamp(factor, 0, 1);

    this.r = clamp(this.r - (factor * 255) | 0, 0, 255);
    this.g = clamp(this.g - (factor * 255) | 0, 0, 255);
    this.b = clamp(this.b - (factor * 255) | 0, 0, 255);
  };

  Color.prototype.fadeIn = function(factor) {
    factor = clamp(factor, 0, 1);

    this.a = this.a + this.a * factor;
    if (this.a > 1) {
      this.a = 1;
    }
  };

  Color.prototype.fadeOut = function(factor) {
    factor = clamp(factor, 0, 1);

    this.a = this.a - this.a * factor;
    if (this.a < 0) {
      this.a = 0;
    }
  };

  Color.prototype.toString = function() {
    if (this.a < 1) {
      return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
    } else {
      return 'rgb(' + this.r + ',' + this.g + ',' + this.b + ')';
    }
  };

  for (var colorName in colorConstants) {
    var colorValue = colorConstants[colorName];
    Color[colorName] = new Color(colorValue.r, colorValue.g, colorValue.b, colorValue.a);
  }

  return Color;
});<|endoftext|>


<commit_before>'use strict';

import uuidv4 from 'uuid/v4';
import Permission from './permission';

export default class Guard {

  /**
   * Create a new instance of {Guard}.
   *
   * @param {any} id This should be the unique id of the guard
   * @param {string} type This should be the type of the guard
  */
  constructor({ id, type }) {
    this._id = id;
    this._type = type;
    this._guards = [];
    this._permissions = [];

    if (!this._id) {
      this._id = uuidv4();
    }

    if (!this._type) {
      throw new Error('Unable to create a guard without specifying it\'s type');
    }

    if (typeof this._type !== 'string') {
      throw new Error('The specified type must be a string');
    }
  }

  /**
   * Retrieve the guard identifier.
   *
   * @return {any}
   */
  getId() {
    return this._id;
  }

  /**
   * Retrieve the guard type.
   *
   * @return {string}
   */
  getType() {
    return this._type;
  }

  /**
   * Retrieve all of the guards from within the inheritance tree.
   *
   * @returns {Array}
   */
  guards() {
    return _.clone(this._guards);
  }

  /**
   * Add a guard to inherit from.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the guard was added successfully
   * @throws {Error} if the specified object is not an instance of {Guard}
   */
  addGuard(guard) {
    if (this.containsGuard(guard)) {
      return true;
    }

    if (!(guard instanceof Guard)) {
      throw new Error('The specified argument must be an instance of {Guard}');
    }

    this._guards.push(guard);

    return this.containsGuard(guard);
  }

  /**
   * Remove a guard that's being inherited.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the guard was removed successfully
   */
  removeGuard(guard) {
    if (this.containsGuard(guard)) {
      for (let i = 0; i < this._guards.length; i++) {
        if (this._guards[i] === guard) {
          this._guards.splice(i, 1);
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Contains a inherited guard.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the Object contains an instance of the specified guard
   */
  containsGuard(guard) {
    for (let i = 0; i < this._guards.length; i++) {
      if (this._guards[i] === guard) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if the specified guard is already inherited.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the guard is already inherited
   */
  doesInherit(guard) {
    let hasChild = this.containsGuard(guard);
    if (!hasChild) {
      for (let i = 0; i < this._guards.length; i++) {
        if (this._guards[i].doesInherit(guard)) {
          return true;
        }
      }
    }
    return hasChild || (this === guard);
  }

  /**
   * Retrieve all of the permissions.
   *
   * @returns {Array}
   */
  permissions() {
    return _.clone(this._permissions);
  }

  /**
   * Add a permission to the guard.
   *
   * @param {Permission} permission
   * @returns {boolean} true if the permission was added successfully
   * @throws {Error} if the specified object is not an instance of {Permission}
   */
  addPermission(permission) {
    if (this.containsPermission(permission)) {
      return true;
    }

    if (!(permission instanceof Permission)) {
      throw new Error('The specified argument must be an instance of {Permission}');
    }

    this._permissions.push(permission);

    return this.containsPermission(permission);
  }

  /**
   * Remove a permission from the guard.
   *
   * @param {Permission} permission
   * @returns {boolean} true if the permission was removed successfully
   */
  removePermission(permission) {
    if (this.containsPermission(permission)) {
      for (let i = 0; i < this._permissions.length; i++) {
        if (this._permissions[i].equals(permission)) {
          this._permissions.splice(i, 1);
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Contains a permission.
   *
   * @param {Permission} permission
   * @returns {boolean} true if the Object contains an instance of the specified permission
   */
  containsPermission(permission) {
    for (let i = 0; i < this._permissions.length; i++) {
      if (this._permissions[i].equals(permission)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if the guard has a permission.
   *
   * This method trickles down it's inheritence and priorities
   * the higher assigned permission.
   *
   * @param {Permission} permission
   * @returns {boolean} true if permission is granted
   */
  hasPermission(permission) {
    if (!(permission instanceof Permission)) {
      if (typeof permission !== 'string') {
        throw new Error('The specified value must be an instance of {Permission} or of type "string"');
      } else {
        permission = new Permission(permission);
      }
    }

    let can = false;

    for (let i = 0; i < this._guards.length; i++) {
      if (this._guards[i].hasPermission(permission)) {
        can = true;
        break;
      }
    }

    for (let i = 0; i < this._permissions.length; i++) {
      let p = this._permissions[i];

      if (p.isNegated() && p.equals(permission.getNegativeValue())) {
        return false;
      }

      if (p.equals(permission.getValue()) || (p.isSuper(permission) && !p.isNegated())) {
        can = true;
      }
    }

    return can;
  }

}
<commit_msg>added an equals method for guards<commit_after>'use strict';

import uuidv4 from 'uuid/v4';
import Permission from './permission';

export default class Guard {

  /**
   * Create a new instance of {Guard}.
   *
   * @param {any} id This should be the unique id of the guard
   * @param {string} type This should be the type of the guard
  */
  constructor({ id, type }) {
    this._id = id;
    this._type = type;
    this._guards = [];
    this._permissions = [];

    if (!this._id) {
      this._id = uuidv4();
    }

    if (!this._type) {
      throw new Error('Unable to create a guard without specifying it\'s type');
    }

    if (typeof this._type !== 'string') {
      throw new Error('The specified type must be a string');
    }
  }

  /**
   * Retrieve the guard identifier.
   *
   * @return {any}
   */
  getId() {
    return this._id;
  }

  /**
   * Retrieve the guard type.
   *
   * @return {string}
   */
  getType() {
    return this._type;
  }

  /**
   * Retrieve all of the guards from within the inheritance tree.
   *
   * @returns {Array}
   */
  guards() {
    return _.clone(this._guards);
  }

  /**
   * Add a guard to inherit from.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the guard was added successfully
   * @throws {Error} if the specified object is not an instance of {Guard}
   */
  addGuard(guard) {
    if (this.containsGuard(guard)) {
      return true;
    }

    if (!(guard instanceof Guard)) {
      throw new Error('The specified argument must be an instance of {Guard}');
    }

    this._guards.push(guard);

    return this.containsGuard(guard);
  }

  /**
   * Remove a guard that's being inherited.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the guard was removed successfully
   */
  removeGuard(guard) {
    if (this.containsGuard(guard)) {
      for (let i = 0; i < this._guards.length; i++) {
        if (this._guards[i] === guard) {
          this._guards.splice(i, 1);
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Contains a inherited guard.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the Object contains an instance of the specified guard
   */
  containsGuard(guard) {
    for (let i = 0; i < this._guards.length; i++) {
      if (this._guards[i].equals(guard)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if the specified guard is already inherited.
   *
   * @param {Guard} guard
   * @returns {boolean} true if the guard is already inherited
   */
  doesInherit(guard) {
    let hasChild = this.containsGuard(guard);
    if (!hasChild) {
      for (let i = 0; i < this._guards.length; i++) {
        if (this._guards[i].doesInherit(guard)) {
          return true;
        }
      }
    }
    return hasChild || (this === guard);
  }

  /**
   * Retrieve all of the permissions.
   *
   * @returns {Array}
   */
  permissions() {
    return _.clone(this._permissions);
  }

  /**
   * Add a permission to the guard.
   *
   * @param {Permission} permission
   * @returns {boolean} true if the permission was added successfully
   * @throws {Error} if the specified object is not an instance of {Permission}
   */
  addPermission(permission) {
    if (this.containsPermission(permission)) {
      return true;
    }

    if (!(permission instanceof Permission)) {
      throw new Error('The specified argument must be an instance of {Permission}');
    }

    this._permissions.push(permission);

    return this.containsPermission(permission);
  }

  /**
   * Remove a permission from the guard.
   *
   * @param {Permission} permission
   * @returns {boolean} true if the permission was removed successfully
   */
  removePermission(permission) {
    if (this.containsPermission(permission)) {
      for (let i = 0; i < this._permissions.length; i++) {
        if (this._permissions[i].equals(permission)) {
          this._permissions.splice(i, 1);
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Contains a permission.
   *
   * @param {Permission} permission
   * @returns {boolean} true if the Object contains an instance of the specified permission
   */
  containsPermission(permission) {
    for (let i = 0; i < this._permissions.length; i++) {
      if (this._permissions[i].equals(permission)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Check if the guard has a permission.
   *
   * This method trickles down it's inheritence and priorities
   * the higher assigned permission.
   *
   * @param {Permission} permission
   * @returns {boolean} true if permission is granted
   */
  hasPermission(permission) {
    if (!(permission instanceof Permission)) {
      if (typeof permission !== 'string') {
        throw new Error('The specified value must be an instance of {Permission} or of type "string"');
      } else {
        permission = new Permission(permission);
      }
    }

    let can = false;

    for (let i = 0; i < this._guards.length; i++) {
      if (this._guards[i].hasPermission(permission)) {
        can = true;
        break;
      }
    }

    for (let i = 0; i < this._permissions.length; i++) {
      let p = this._permissions[i];

      if (p.isNegated() && p.equals(permission.getNegativeValue())) {
        return false;
      }

      if (p.equals(permission.getValue()) || (p.isSuper(permission) && !p.isNegated())) {
        can = true;
      }
    }

    return can;
  }

  /**
   * Check if a guard is equal to the guard.
   *
   * @param {Guard} guard
   * @returns {boolean} true if they are the same
   */
  equals(guard) {
    return ((guard instanceof Guard) && (guard.getId() === this.getId()) && (guard.getType() === this.getType()));
  }

}
<|endoftext|>


<commit_before>'use strict'

/**
 * Module Depdendencies
 * @ignore
 */
const SupportedKeyTypes = require('./SupportedKeyTypes')
const RSA = require('./RSA')
const ECDSA = require('./ECDSA')
const EDDSA = require('./EDDSA')

/**
 * supportedKeyTypes
 * @ignore
 */
const supportedKeyTypes = new SupportedKeyTypes()

// RSA
supportedKeyTypes.define([
  {
    kty: 'RSA',
    oid: '1.2.840.113549.1.1.1',
    algParameters: '0500',
    version: 'two-prime',
  }
], RSA)

// ECDSA
supportedKeyTypes.define([
  {
    kty: 'EC',
    crv: 'K-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.10',
    algParameters: '06052b8104000a',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.2.840.10045.3.1.7',
    algParameters: '06082a8648ce3d030107',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-384',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.34',
    algParameters: '06052b81040022',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-512',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.35',
    algParameters: '06052b81040023',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
], ECDSA)

// EDDSA
supportedKeyTypes.define([
], EDDSA)

/**
 * Export
 * @ignore
 */
module.exports = supportedKeyTypes
<commit_msg>fix(types): correct NIST EC curve name<commit_after>'use strict'

/**
 * Module Depdendencies
 * @ignore
 */
const SupportedKeyTypes = require('./SupportedKeyTypes')
const RSA = require('./RSA')
const ECDSA = require('./ECDSA')
const EDDSA = require('./EDDSA')

/**
 * supportedKeyTypes
 * @ignore
 */
const supportedKeyTypes = new SupportedKeyTypes()

// RSA
supportedKeyTypes.define([
  {
    kty: 'RSA',
    oid: '1.2.840.113549.1.1.1',
    algParameters: '0500',
    version: 'two-prime',
  }
], RSA)

// ECDSA
supportedKeyTypes.define([
  {
    kty: 'EC',
    crv: 'K-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.10',
    algParameters: '06052b8104000a',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.2.840.10045.3.1.7',
    algParameters: '06082a8648ce3d030107',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-384',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.34',
    algParameters: '06052b81040022',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-521',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.35',
    algParameters: '06052b81040023',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
], ECDSA)

// EDDSA
supportedKeyTypes.define([
], EDDSA)

/**
 * Export
 * @ignore
 */
module.exports = supportedKeyTypes
<|endoftext|>


<commit_before>'use strict'

/**
 * Module Depdendencies
 * @ignore
 */
const SupportedKeyTypes = require('./SupportedKeyTypes')
const RSA = require('./RSA')
const ECDSA = require('./ECDSA')
const EDDSA = require('./EDDSA')

/**
 * supportedKeyTypes
 * @ignore
 */
const supportedKeyTypes = new SupportedKeyTypes()

// RSA
supportedKeyTypes.define([
  {
    kty: 'RSA',
    oid: '1.2.840.113549.1.1.1',
    algParameters: '0500',
    version: 'two-prime',
  }
], RSA)

// ECDSA
supportedKeyTypes.define([
  {
    kty: 'EC',
    crv: 'K-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.10',
    algParameters: '06052b8104000a',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.2.840.10045.3.1.7',
    algParameters: '06082a8648ce3d030107',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  // {
  //   kty: 'EC',
  //   crv: 'P-384',
  //   oid: '',
  //   namedCurve: '',
  //   algParameters: '',
  //   keyVersion: 1,
  //   infoVersion: 'two-prime',
  // },
  // {
  //   kty: 'EC',
  //   crv: 'P-512',
  //   oid: '',
  //   namedCurve: '',
  //   algParameters: '',
  //   keyVersion: 1,
  //   infoVersion: 'two-prime',
  // },
], ECDSA)

// EDDSA
supportedKeyTypes.define([
], EDDSA)

/**
 * Export
 * @ignore
 */
module.exports = supportedKeyTypes
<commit_msg>feat(algorithms): enable P384 and P512<commit_after>'use strict'

/**
 * Module Depdendencies
 * @ignore
 */
const SupportedKeyTypes = require('./SupportedKeyTypes')
const RSA = require('./RSA')
const ECDSA = require('./ECDSA')
const EDDSA = require('./EDDSA')

/**
 * supportedKeyTypes
 * @ignore
 */
const supportedKeyTypes = new SupportedKeyTypes()

// RSA
supportedKeyTypes.define([
  {
    kty: 'RSA',
    oid: '1.2.840.113549.1.1.1',
    algParameters: '0500',
    version: 'two-prime',
  }
], RSA)

// ECDSA
supportedKeyTypes.define([
  {
    kty: 'EC',
    crv: 'K-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.10',
    algParameters: '06052b8104000a',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-256',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.2.840.10045.3.1.7',
    algParameters: '06082a8648ce3d030107',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-384',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.34',
    algParameters: '06052b81040022',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
  {
    kty: 'EC',
    crv: 'P-512',
    oid: '1.2.840.10045.2.1',
    namedCurve: '1.3.132.0.35',
    algParameters: '06052b81040023',
    keyVersion: 1,
    infoVersion: 'two-prime',
  },
], ECDSA)

// EDDSA
supportedKeyTypes.define([
], EDDSA)

/**
 * Export
 * @ignore
 */
module.exports = supportedKeyTypes
<|endoftext|>


<commit_before>Util.Animation = u.a = new function() {

	// translate3d support?
	this.support3d = function() {
		// only run detection once
		if(this._support3d === undefined) {
			var node = u.ae(document.body, "div");

			try {
				u.as(node, "transform", "translate3d(10px, 10px, 10px)");
				if(u.gcs(node, "transform").match(/matrix3d\(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1\)/)) {
					this._support3d = true;
				}
	 			else {
					this._support3d = false;
				}
			}
			catch(exception) {
//				u.bug("exception:" + exception)
				this._support3d = false;
			}

			document.body.removeChild(node);
		}
//		u.bug("3d test result:" + this._support3d);
		return this._support3d;
	}

	/**
	* Apply CSS transition to node
	*/
	this.transition = function(node, transition, callback) {
		u.bug("add transition:", node, transition, callback);

		try {

			// get duration
			var duration = transition.match(/[0-9.]+[ms]+/g);
			if(duration) {
		//		u.bug(duration[0]);
				node.duration = duration[0].match("ms") ? parseFloat(duration[0]) : (parseFloat(duration[0]) * 1000);

				// custom transition callback
				if(callback) {
//					u.bug("custom transition callback:" + callback + ", " + u.nodeId(node))

					var transitioned;
					transitioned = (function(event) {

//						u.bug("custom transitioned:" + callback  + ", " + u.nodeId(event.target) + ", " + u.nodeId(this) + ", " + typeof(callback) + ", " + typeof(this[callback]))
						u.e.removeEvent(event.target, u.a.transitionEndEventName(), transitioned);

						if(event.target == this) {

							u.a.transition(this, "none");

							if(fun(callback)) {
								var key = u.randomString(4);
								node[key] = callback;
								node[key](event);
								delete node[key];
								callback = null;
							}
							else if(fun(this[callback])) {
//								u.bug("callback to: " + callback + ", " + this[callback])
								this[callback](event);
								// this[callback] = null;
							}

						}
						else {
//							u.e.kill(event);
						}
					});

					u.e.addEvent(node, u.a.transitionEndEventName(), transitioned);
				}
				else {
//					u.bug("standard transition callback:" + u.nodeId(node))

					// only set transitionEnd listener if transition has duration
					u.e.addEvent(node, u.a.transitionEndEventName(), this._transitioned);
				}

			}
			else {
				node.duration = false;
			}

			u.as(node, "transition", transition);
//			node.style[this.vendor("Transition")] = transition;

		}
		catch(exception) {
			u.exception("u.a.transition", arguments, exception);
		}

	}

	// helper function to determine transitionend event name
	// Opera and Chrome introduced prefixed event name in early versions
	this.transitionEndEventName = function() {

		if(!this._transition_end_event_name) {

			// default name
			this._transition_end_event_name = "transitionend";

			var transitions = {
				"transition": "transitionend",
				"MozTransition": "transitionend",
				"msTransition": "transitionend",
				"webkitTransition": "webkitTransitionEnd",
				"OTransition": "otransitionend"
			};

			var x, div = document.createElement("div");
			for(x in transitions){
				if(typeof(div.style[x]) !== "undefined") {
					this._transition_end_event_name = transitions[x];
					break;
				}
			}
		}

		return this._transition_end_event_name;
	}

	// transition end handler
	// not for chained transitions - will reset node.transitioned and remove transition
	this._transitioned = function(event) {
		// u.bug("default transitioned:", this);

		// Do not remove event listener and transition unless callback stems from correct node
		if(event.target == this) {

			u.e.removeEvent(event.target, u.a.transitionEndEventName(), u.a._transitioned);

			// transition should be removed here to be cleared before callback
			u.a.transition(event.target, "none");

			// only do callback to correct targets
			if(fun(this.transitioned)) {
				this.transitioned_before = this.transitioned;

				this.transitioned(event);

				// Unless transition callback has changed
				if(this.transitioned === this.transitioned_before) {
					delete this.transitioned;
				}

			}

		}

	}

	// EXPERIMENTAL: remove transform, because Firefox 23 makes render-error, when returning to 0 in translates
	// DEPRECATED: excess code to replicate one-liner
	// this.removeTransform = function(node) {
	// 	u.as(node, "transform", "none");
	//
	// }

	/**
	* Simple translate cross-browser
	*/
	this.translate = function(node, x, y) {

		// use translate3d when supported as it is more often hardware accelerated
		if(this.support3d()) {
			u.as(node, "transform", "translate3d("+x+"px, "+y+"px, 0)");
		}
		else {
			u.as(node, "transform", "translate("+x+"px, "+y+"px)");
		}

		// new value holder
		node._x = x;
		node._y = y;

		// update dom
		node.offsetHeight;
	}

	this.rotate = function(node, deg) {
		u.as(node, "transform", "rotate("+deg+"deg)");
//		node.style[this.vendor("Transform")] = "rotate("+deg+"deg)";

		node._rotation = deg;

		// update dom
		node.offsetHeight;
	}

	this.scale = function(node, scale) {
		u.as(node, "transform", "scale("+scale+")");
//		node.style[this.vendor("Transform")] = "scale("+scale+")";

		node._scale = scale;

		// update dom
		node.offsetHeight;
	}

	this.setOpacity = this.opacity = function(node, opacity) {
		u.as(node, "opacity", opacity);
//		node.style.opacity = opacity;

		node._opacity = opacity;

		// update dom
		node.offsetHeight;
	}

	this.setWidth = this.width = function(node, width) {
		width = width.toString().match(/\%|auto|px/) ? width : (width + "px");
		node.style.width = width;

		node._width = width;

		// update dom
		node.offsetHeight;
	}

	this.setHeight = this.height = function(node, height) {
		height = height.toString().match(/\%|auto|px/) ? height : (height + "px");
		node.style.height = height;

		node._height = height;

		// update dom
		node.offsetHeight;
	}

	this.setBgPos = this.bgPos = function(node, x, y) {
		x = x.toString().match(/\%|auto|px|center|top|left|bottom|right/) ? x : (x + "px");
		y = y.toString().match(/\%|auto|px|center|top|left|bottom|right/) ? y : (y + "px");
		node.style.backgroundPosition = x + " " + y;

		node._bg_x = x;
		node._bg_y = y;

		// update dom
		node.offsetHeight;
	}

	this.setBgColor = this.bgColor = function(node, color) {
		node.style.backgroundColor = color;

		node._bg_color = color;

		// update dom
		node.offsetHeight;
	}

	// Combined Transforms. Make it possible to run several animation effects at the same time (EX: rotate + scale + translate).
	// DEPRECATED: this can easily be done using u.as now
	//
	// // Rotate & Scale
	// this.rotateScale = function(node, deg, scale) {
	//
	// 	u.as(node, "transform", "rotate("+deg+"deg) scale("+scale+")");
	//
	// 	node.style[this.vendor("Transform")] = "rotate("+deg+"deg) scale("+scale+")";
	// 	node._rotation = deg;
	// 	node._scale = scale;
	//
	// 	// update dom
	// 	node.offsetHeight;
	// }
	//
	// // Scale, Rotate, Translate
	// this.scaleRotateTranslate = function(node, scale, deg, x, y) {
	//
	// 	if(this.support3d()) {
	// 		node.style[this.vendor("Transform")] = "scale("+scale+") rotate("+deg+"deg) translate3d("+x+"px, "+y+"px, 0)";
	// 	}
	// 	else {
	// 		node.style[this.vendor("Transform")] = "scale("+scale+") rotate("+deg+"deg) translate("+x+"px, "+y+"px)";
	// 	}
	//
	// 	// store value
	// 	node._rotation = deg;
	// 	node._scale = scale;
	// 	node._x = x;
	// 	node._y = y;
	//
	// 	// update dom
	// 	node.offsetHeight;
	// }

	this._animationqueue = {};
	this.requestAnimationFrame = function(node, callback, duration) {
//		u.bug("requestAnimationFrame:" + callback + ", " + duration + ", " + u.nodeId(node) + ", " + u.a._requestAnimationId)

		if(!u.a.__animation_frame_start) {
			u.a.__animation_frame_start = Date.now();
		}
		// add animation to stack
//		var start = Date.now() - u.a.__animation_frame_start;
		var id = u.randomString();

//		u.bug("now:" + Date.now() + ", " + start)

		// create object with all information
		u.a._animationqueue[id] = {};
		u.a._animationqueue[id].id = id;
		u.a._animationqueue[id].node = node;
		u.a._animationqueue[id].callback = callback;
//		u.a._animationqueue[id].start = start;
		u.a._animationqueue[id].duration = duration;

		// TODO: timers are not very precise - is this a good idea+
		// add duration timer
		u.t.setTimer(u.a, function() {u.a.finalAnimationFrame(id)}, duration);

		// first addition, set up animationframe loop
		if(!u.a._animationframe) {

			// create function references
			window._requestAnimationFrame = eval(u.vendorProperty("requestAnimationFrame"));
			window._cancelAnimationFrame = eval(u.vendorProperty("cancelAnimationFrame"));

			// animationframe iterator
			u.a._animationframe = function(timestamp) {

//				u.bug("frame:" + timestamp);

				var id, animation;
				for(id in u.a._animationqueue) {

					animation = u.a._animationqueue[id];

					if(!animation["__animation_frame_start_"+id]) {
						// add animation to stack
						animation["__animation_frame_start_"+id] = timestamp;
//						animation["__animation_frame_start_"+id] = (Date.now() - u.a.__animation_frame_start) + timestamp;
//						u.bug("now:" + animation["__animation_frame_start_"+id])
					}

					// progress callback
					if(fun(animation.node[animation.callback])) {
						animation.node[animation.callback]((timestamp-animation["__animation_frame_start_"+id]) / animation.duration);
					}
				}

				// continue animationFrame loop
				if(Object.keys(u.a._animationqueue).length) {

					u.a._requestAnimationId = window._requestAnimationFrame(u.a._animationframe);
				}
			}
		}

		// loop will be pause when no animations are active
		// restart requestAnimationFrame loop if it is paused
		if(!u.a._requestAnimationId) {

//			u.bug("restart")
			u.a._requestAnimationId = window._requestAnimationFrame(u.a._animationframe);
//			u.bug("u.a._requestAnimationId:" + u.a._requestAnimationId)
		}

		return id;
	}

	this.finalAnimationFrame = function(id) {
//		u.bug("finalAnimationFrame:" + ", " + id + ", " + u.a._requestAnimationId);

		var animation = u.a._animationqueue[id];
		animation["__animation_frame_start_"+id] = false;
		if(fun(animation.node[animation.callback])) {
			animation.node[animation.callback](1);
		}

		if(fun(animation.node.transitioned)) {
//			u.bug("callback:" + u.nodeId(animation.node));
			animation.node.transitioned({});
		}

		// delete animation;
		// delete animation;
		delete u.a._animationqueue[id];

		// continue animationFrame loop
		if(!Object.keys(u.a._animationqueue).length) {

			this.cancelAnimationFrame(id);
		}
	}

	this.cancelAnimationFrame = function(id) {
//		u.bug("cancelAnimationFrame:" + ", " + id + ", " + u.a._requestAnimationId);

		if(id && u.a._animationqueue[id]) {

			// delete animation;
			delete u.a._animationqueue[id];
		}

		if(u.a._requestAnimationId) {

//				u.bug(this.vendor("cancelAnimationFrame"));
			window._cancelAnimationFrame(u.a._requestAnimationId);

			u.a.__animation_frame_start = false;
			u.a._requestAnimationId = false;
		}
	}

}
<commit_msg>remove u.bug<commit_after>Util.Animation = u.a = new function() {

	// translate3d support?
	this.support3d = function() {
		// only run detection once
		if(this._support3d === undefined) {
			var node = u.ae(document.body, "div");

			try {
				u.as(node, "transform", "translate3d(10px, 10px, 10px)");
				if(u.gcs(node, "transform").match(/matrix3d\(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 10, 10, 1\)/)) {
					this._support3d = true;
				}
	 			else {
					this._support3d = false;
				}
			}
			catch(exception) {
//				u.bug("exception:" + exception)
				this._support3d = false;
			}

			document.body.removeChild(node);
		}
//		u.bug("3d test result:" + this._support3d);
		return this._support3d;
	}

	/**
	* Apply CSS transition to node
	*/
	this.transition = function(node, transition, callback) {
		// u.bug("add transition:", node, transition, callback);

		try {

			// get duration
			var duration = transition.match(/[0-9.]+[ms]+/g);
			if(duration) {
		//		u.bug(duration[0]);
				node.duration = duration[0].match("ms") ? parseFloat(duration[0]) : (parseFloat(duration[0]) * 1000);

				// custom transition callback
				if(callback) {
//					u.bug("custom transition callback:" + callback + ", " + u.nodeId(node))

					var transitioned;
					transitioned = (function(event) {

//						u.bug("custom transitioned:" + callback  + ", " + u.nodeId(event.target) + ", " + u.nodeId(this) + ", " + typeof(callback) + ", " + typeof(this[callback]))
						u.e.removeEvent(event.target, u.a.transitionEndEventName(), transitioned);

						if(event.target == this) {

							u.a.transition(this, "none");

							if(fun(callback)) {
								var key = u.randomString(4);
								node[key] = callback;
								node[key](event);
								delete node[key];
								callback = null;
							}
							else if(fun(this[callback])) {
//								u.bug("callback to: " + callback + ", " + this[callback])
								this[callback](event);
								// this[callback] = null;
							}

						}
						else {
//							u.e.kill(event);
						}
					});

					u.e.addEvent(node, u.a.transitionEndEventName(), transitioned);
				}
				else {
//					u.bug("standard transition callback:" + u.nodeId(node))

					// only set transitionEnd listener if transition has duration
					u.e.addEvent(node, u.a.transitionEndEventName(), this._transitioned);
				}

			}
			else {
				node.duration = false;
			}

			u.as(node, "transition", transition);
//			node.style[this.vendor("Transition")] = transition;

		}
		catch(exception) {
			u.exception("u.a.transition", arguments, exception);
		}

	}

	// helper function to determine transitionend event name
	// Opera and Chrome introduced prefixed event name in early versions
	this.transitionEndEventName = function() {

		if(!this._transition_end_event_name) {

			// default name
			this._transition_end_event_name = "transitionend";

			var transitions = {
				"transition": "transitionend",
				"MozTransition": "transitionend",
				"msTransition": "transitionend",
				"webkitTransition": "webkitTransitionEnd",
				"OTransition": "otransitionend"
			};

			var x, div = document.createElement("div");
			for(x in transitions){
				if(typeof(div.style[x]) !== "undefined") {
					this._transition_end_event_name = transitions[x];
					break;
				}
			}
		}

		return this._transition_end_event_name;
	}

	// transition end handler
	// not for chained transitions - will reset node.transitioned and remove transition
	this._transitioned = function(event) {
		// u.bug("default transitioned:", this);

		// Do not remove event listener and transition unless callback stems from correct node
		if(event.target == this) {

			u.e.removeEvent(event.target, u.a.transitionEndEventName(), u.a._transitioned);

			// transition should be removed here to be cleared before callback
			u.a.transition(event.target, "none");

			// only do callback to correct targets
			if(fun(this.transitioned)) {
				this.transitioned_before = this.transitioned;

				this.transitioned(event);

				// Unless transition callback has changed
				if(this.transitioned === this.transitioned_before) {
					delete this.transitioned;
				}

			}

		}

	}

	// EXPERIMENTAL: remove transform, because Firefox 23 makes render-error, when returning to 0 in translates
	// DEPRECATED: excess code to replicate one-liner
	// this.removeTransform = function(node) {
	// 	u.as(node, "transform", "none");
	//
	// }

	/**
	* Simple translate cross-browser
	*/
	this.translate = function(node, x, y) {

		// use translate3d when supported as it is more often hardware accelerated
		if(this.support3d()) {
			u.as(node, "transform", "translate3d("+x+"px, "+y+"px, 0)");
		}
		else {
			u.as(node, "transform", "translate("+x+"px, "+y+"px)");
		}

		// new value holder
		node._x = x;
		node._y = y;

		// update dom
		node.offsetHeight;
	}

	this.rotate = function(node, deg) {
		u.as(node, "transform", "rotate("+deg+"deg)");
//		node.style[this.vendor("Transform")] = "rotate("+deg+"deg)";

		node._rotation = deg;

		// update dom
		node.offsetHeight;
	}

	this.scale = function(node, scale) {
		u.as(node, "transform", "scale("+scale+")");
//		node.style[this.vendor("Transform")] = "scale("+scale+")";

		node._scale = scale;

		// update dom
		node.offsetHeight;
	}

	this.setOpacity = this.opacity = function(node, opacity) {
		u.as(node, "opacity", opacity);
//		node.style.opacity = opacity;

		node._opacity = opacity;

		// update dom
		node.offsetHeight;
	}

	this.setWidth = this.width = function(node, width) {
		width = width.toString().match(/\%|auto|px/) ? width : (width + "px");
		node.style.width = width;

		node._width = width;

		// update dom
		node.offsetHeight;
	}

	this.setHeight = this.height = function(node, height) {
		height = height.toString().match(/\%|auto|px/) ? height : (height + "px");
		node.style.height = height;

		node._height = height;

		// update dom
		node.offsetHeight;
	}

	this.setBgPos = this.bgPos = function(node, x, y) {
		x = x.toString().match(/\%|auto|px|center|top|left|bottom|right/) ? x : (x + "px");
		y = y.toString().match(/\%|auto|px|center|top|left|bottom|right/) ? y : (y + "px");
		node.style.backgroundPosition = x + " " + y;

		node._bg_x = x;
		node._bg_y = y;

		// update dom
		node.offsetHeight;
	}

	this.setBgColor = this.bgColor = function(node, color) {
		node.style.backgroundColor = color;

		node._bg_color = color;

		// update dom
		node.offsetHeight;
	}

	// Combined Transforms. Make it possible to run several animation effects at the same time (EX: rotate + scale + translate).
	// DEPRECATED: this can easily be done using u.as now
	//
	// // Rotate & Scale
	// this.rotateScale = function(node, deg, scale) {
	//
	// 	u.as(node, "transform", "rotate("+deg+"deg) scale("+scale+")");
	//
	// 	node.style[this.vendor("Transform")] = "rotate("+deg+"deg) scale("+scale+")";
	// 	node._rotation = deg;
	// 	node._scale = scale;
	//
	// 	// update dom
	// 	node.offsetHeight;
	// }
	//
	// // Scale, Rotate, Translate
	// this.scaleRotateTranslate = function(node, scale, deg, x, y) {
	//
	// 	if(this.support3d()) {
	// 		node.style[this.vendor("Transform")] = "scale("+scale+") rotate("+deg+"deg) translate3d("+x+"px, "+y+"px, 0)";
	// 	}
	// 	else {
	// 		node.style[this.vendor("Transform")] = "scale("+scale+") rotate("+deg+"deg) translate("+x+"px, "+y+"px)";
	// 	}
	//
	// 	// store value
	// 	node._rotation = deg;
	// 	node._scale = scale;
	// 	node._x = x;
	// 	node._y = y;
	//
	// 	// update dom
	// 	node.offsetHeight;
	// }

	this._animationqueue = {};
	this.requestAnimationFrame = function(node, callback, duration) {
//		u.bug("requestAnimationFrame:" + callback + ", " + duration + ", " + u.nodeId(node) + ", " + u.a._requestAnimationId)

		if(!u.a.__animation_frame_start) {
			u.a.__animation_frame_start = Date.now();
		}
		// add animation to stack
//		var start = Date.now() - u.a.__animation_frame_start;
		var id = u.randomString();

//		u.bug("now:" + Date.now() + ", " + start)

		// create object with all information
		u.a._animationqueue[id] = {};
		u.a._animationqueue[id].id = id;
		u.a._animationqueue[id].node = node;
		u.a._animationqueue[id].callback = callback;
//		u.a._animationqueue[id].start = start;
		u.a._animationqueue[id].duration = duration;

		// TODO: timers are not very precise - is this a good idea+
		// add duration timer
		u.t.setTimer(u.a, function() {u.a.finalAnimationFrame(id)}, duration);

		// first addition, set up animationframe loop
		if(!u.a._animationframe) {

			// create function references
			window._requestAnimationFrame = eval(u.vendorProperty("requestAnimationFrame"));
			window._cancelAnimationFrame = eval(u.vendorProperty("cancelAnimationFrame"));

			// animationframe iterator
			u.a._animationframe = function(timestamp) {

//				u.bug("frame:" + timestamp);

				var id, animation;
				for(id in u.a._animationqueue) {

					animation = u.a._animationqueue[id];

					if(!animation["__animation_frame_start_"+id]) {
						// add animation to stack
						animation["__animation_frame_start_"+id] = timestamp;
//						animation["__animation_frame_start_"+id] = (Date.now() - u.a.__animation_frame_start) + timestamp;
//						u.bug("now:" + animation["__animation_frame_start_"+id])
					}

					// progress callback
					if(fun(animation.node[animation.callback])) {
						animation.node[animation.callback]((timestamp-animation["__animation_frame_start_"+id]) / animation.duration);
					}
				}

				// continue animationFrame loop
				if(Object.keys(u.a._animationqueue).length) {

					u.a._requestAnimationId = window._requestAnimationFrame(u.a._animationframe);
				}
			}
		}

		// loop will be pause when no animations are active
		// restart requestAnimationFrame loop if it is paused
		if(!u.a._requestAnimationId) {

//			u.bug("restart")
			u.a._requestAnimationId = window._requestAnimationFrame(u.a._animationframe);
//			u.bug("u.a._requestAnimationId:" + u.a._requestAnimationId)
		}

		return id;
	}

	this.finalAnimationFrame = function(id) {
//		u.bug("finalAnimationFrame:" + ", " + id + ", " + u.a._requestAnimationId);

		var animation = u.a._animationqueue[id];
		animation["__animation_frame_start_"+id] = false;
		if(fun(animation.node[animation.callback])) {
			animation.node[animation.callback](1);
		}

		if(fun(animation.node.transitioned)) {
//			u.bug("callback:" + u.nodeId(animation.node));
			animation.node.transitioned({});
		}

		// delete animation;
		// delete animation;
		delete u.a._animationqueue[id];

		// continue animationFrame loop
		if(!Object.keys(u.a._animationqueue).length) {

			this.cancelAnimationFrame(id);
		}
	}

	this.cancelAnimationFrame = function(id) {
//		u.bug("cancelAnimationFrame:" + ", " + id + ", " + u.a._requestAnimationId);

		if(id && u.a._animationqueue[id]) {

			// delete animation;
			delete u.a._animationqueue[id];
		}

		if(u.a._requestAnimationId) {

//				u.bug(this.vendor("cancelAnimationFrame"));
			window._cancelAnimationFrame(u.a._requestAnimationId);

			u.a.__animation_frame_start = false;
			u.a._requestAnimationId = false;
		}
	}

}
<|endoftext|>


<commit_before>var classnames = require('classnames');
var React = require('react/addons');
var ViewContent = require('./ViewContent');

module.exports = React.createClass({
	displayName: 'Alertbar',
	propTypes: {
		children: React.PropTypes.node,
		className: React.PropTypes.string,
		height: React.PropTypes.string,
		pulse: React.PropTypes.bool,
		type: React.PropTypes.oneOf(['default', 'primary', 'success', 'warning', 'danger'])
	},
	getDefaultProps () {
		return {
			height: '30px',
			type: 'default'
		};
	},
	render () {
		var className = classnames(this.props.className, this.props.type, {
			'Alertbar': true,
			'pulse': this.props.pulse
		});
		var content = this.props.pulse ?
{this.props.children}
 : this.props.children;

		return (
			<ViewContent height={this.props.height} className={className}>
				{content}
			</ViewContent>
		);
	}
});
<commit_msg>cleanup Alertbar<commit_after>var React = require('react/addons');

var blacklist = require('blacklist');
var classnames = require('classnames');

module.exports = React.createClass({
	displayName: 'Alertbar',
	propTypes: {
		children: React.PropTypes.node.isRequired,
		className: React.PropTypes.string,
		pulse: React.PropTypes.bool,
		type: React.PropTypes.oneOf(['default', 'primary', 'success', 'warning', 'danger'])
	},

	getDefaultProps () {
		return {
			type: 'default'
		}
	},

	render () {
		var { pulse } = this.props
		var className = classnames('Alertbar', this.props.className, this.props.type, { 'pulse': pulse });

		if (pulse) {
			var otherProps = blacklist(this.props, 'children')

			return (

{this.props.children}

			)
		}

		return

	}
});
<|endoftext|>


<commit_before>'use strict'
var yo = require('yo-yo')
var style = require('./styles/treeView')
var ui = require('../helpers/ui')

class TreeView {

  constructor (opts) {
    function noop (node) {
    }
    this.beforeJsonNodeRendered = opts.beforeJsonNodeRendered || noop
    this.beforeJsonValueRendered = opts.beforeJsonValueRendered || noop
    this.view = null
    this.cssLabel = ui.formatCss(style.label)
    this.cssList = ui.formatCss(style.list)
  }

  render (json) {
    if (!json) {
      json = {}
    }
    var view = yo`<div>${this.renderProperties(json, true)}</div>`
    if (!this.view) {
      this.view = view
    }
    return view
  }

  update (json) {
    if (this.view) {
      yo.update(this.view, this.render(json), {onBeforeElUpdated: (fromEl, toEl) => {
        toEl.style.display = fromEl.style.display
        toEl.className = fromEl.className
        return true
      }})
    }
  }

  renderObject (item, key, expand) {
    var label
    if (item instanceof Array || item instanceof Object) {
      var properties = this.renderProperties(item, false)
      label = yo`<span style=${this.cssLabel}><label style='width: 10px' id='caret'></label><label>${key} - ${properties.length} items</label></span>`
      var list = yo`<ul style=${this.cssList}>${properties}</ol>`
      list.style.display = expand ? 'block' : 'none'
      label.firstElementChild.className = expand ? 'fa fa-caret-down' : 'fa fa-caret-right'
      label.onclick = function () {
        this.firstElementChild.className = this.firstElementChild.className === 'fa fa-caret-right' ? 'fa fa-caret-down' : 'fa fa-caret-right'
        var list = this.parentElement.querySelector('ul')
        list.style.display = list.style.display === 'none' ? 'block' : 'none'
      }
      if (this.beforeJsonNodeRendered) {
        this.beforeJsonNodeRendered(label, item, key)
      }
      return yo`<li style=${this.cssList}>${label}${list}</li>`
    } else {
      label = yo`<label style=${this.cssLabel}>${key}</label>`
      if (this.beforeJsonValueRendered) {
        this.beforeJsonValueRendered(label, item, key)
      }
      return yo`<li style=${this.cssList}>${label} : <span style=${this.cssLabel} >${item}</span></li>`
    }
  }

  renderProperties (json, expand) {
    var properties = Object.keys(json).map((innerkey) => {
      return this.renderObject(json[innerkey], innerkey, expand)
    })
    return properties
  }
}

module.exports = TreeView
<commit_msg>display empty treeview instead of nothing<commit_after>'use strict'
var yo = require('yo-yo')
var style = require('./styles/treeView')
var ui = require('../helpers/ui')

class TreeView {

  constructor (opts) {
    function noop (node) {
    }
    this.beforeJsonNodeRendered = opts.beforeJsonNodeRendered || noop
    this.beforeJsonValueRendered = opts.beforeJsonValueRendered || noop
    this.view = null
    this.cssLabel = ui.formatCss(style.label)
    this.cssList = ui.formatCss(style.list)
  }

  render (json) {
    if (!json || !Object.keys(json).length) {
      json = {' - ': ' - '}
    }
    var view = yo`<div>${this.renderProperties(json, true)}</div>`
    if (!this.view) {
      this.view = view
    }
    return view
  }

  update (json) {
    if (this.view) {
      yo.update(this.view, this.render(json), {onBeforeElUpdated: (fromEl, toEl) => {
        toEl.style.display = fromEl.style.display
        toEl.className = fromEl.className
        return true
      }})
    }
  }

  renderObject (item, key, expand) {
    var label
    if (item instanceof Array || item instanceof Object) {
      var properties = this.renderProperties(item, false)
      label = yo`<span style=${this.cssLabel}><label style='width: 10px' id='caret'></label><label>${key} - ${properties.length} items</label></span>`
      var list = yo`<ul style=${this.cssList}>${properties}</ol>`
      list.style.display = expand ? 'block' : 'none'
      label.firstElementChild.className = expand ? 'fa fa-caret-down' : 'fa fa-caret-right'
      label.onclick = function () {
        this.firstElementChild.className = this.firstElementChild.className === 'fa fa-caret-right' ? 'fa fa-caret-down' : 'fa fa-caret-right'
        var list = this.parentElement.querySelector('ul')
        list.style.display = list.style.display === 'none' ? 'block' : 'none'
      }
      if (this.beforeJsonNodeRendered) {
        this.beforeJsonNodeRendered(label, item, key)
      }
      return yo`<li style=${this.cssList}>${label}${list}</li>`
    } else {
      label = yo`<label style=${this.cssLabel}>${key}</label>`
      if (this.beforeJsonValueRendered) {
        this.beforeJsonValueRendered(label, item, key)
      }
      return yo`<li style=${this.cssList}>${label} : <span style=${this.cssLabel} >${item}</span></li>`
    }
  }

  renderProperties (json, expand) {
    var properties = Object.keys(json).map((innerkey) => {
      return this.renderObject(json[innerkey], innerkey, expand)
    })
    return properties
  }
}

module.exports = TreeView
<|endoftext|>