text: var assert = require('assert')
  var base58check = require('bs58check')
  var crypto = require('./crypto')
  var networks = require('./networks')
  
  var BigInteger = require('bigi')
  var ECKey = require('./eckey')
  var ECPubKey = require('./ecpubkey')
  
  var ecurve = require('ecurve')
  var curve = ecurve.getCurveByName('secp256k1')
  
  function findBIP32ParamsByVersion(version) {
    for (var name in networks) {
      var network = networks[name]
  
      for (var type in network.bip32) {
        if (version != network.bip32[type]) continue
  
        return {
          isPrivate: (type === 'private'),
          network: network
        }
      }
    }
  
    assert(false, 'Could not find version ' + version.toString(16))
  }
  
  function HDNode(K, chainCode, network) {
    network = network || networks.bitcoin
  
    assert(Buffer.isBuffer(chainCode), 'Expected Buffer, got ' + chainCode)
    assert.equal(chainCode.length, 32, 'Expected chainCode length of 32, got ' + chainCode.length)
    assert(network.bip32, 'Unknown BIP32 constants for network')
  
    this.chainCode = chainCode
    this.depth = 0
    this.index = 0
    this.network = network
  
    if (K instanceof BigInteger) {
      this.privKey = new ECKey(K, true)
      this.pubKey = this.privKey.pub
    } else {
      this.pubKey = new ECPubKey(K, true)
    }
  }
  
  HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
  HDNode.HIGHEST_BIT = 0x80000000
  HDNode.LENGTH = 78
  
  HDNode.fromSeedBuffer = function(seed, network) {
    assert(Buffer.isBuffer(seed), 'Expected Buffer, got ' + seed)
    assert(seed.length >= 16, 'Seed should be at least 128 bits')
    assert(seed.length <= 64, 'Seed should be at most 512 bits')
  
    var I = crypto.HmacSHA512(seed, HDNode.MASTER_SECRET)
    var IL = I.slice(0, 32)
    var IR = I.slice(32)
  
    // In case IL is 0 or >= n, the master key is invalid
    // This is handled by `new ECKey` in the HDNode constructor
    var pIL = BigInteger.fromBuffer(IL)
  
    return new HDNode(pIL, IR, network)
  }
  
  HDNode.fromSeedHex = function(hex, network) {
    return HDNode.fromSeedBuffer(new Buffer(hex, 'hex'), network)
  }
  
  HDNode.fromBase58 = function(string) {
    return HDNode.fromBuffer(base58check.decode(string))
  }
  
  HDNode.fromBuffer = function(buffer) {
    assert.strictEqual(buffer.length, HDNode.LENGTH, 'Invalid buffer length')
  
    // 4 byte: version bytes
    var version = buffer.readUInt32BE(0)
    var params = findBIP32ParamsByVersion(version)
  
    // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
    var depth = buffer.readUInt8(4)
  
    // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
    var parentFingerprint = buffer.readUInt32BE(5)
    if (depth === 0) {
      assert.strictEqual(parentFingerprint, 0x00000000, 'Invalid parent fingerprint')
    }
  
    // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
    // This is encoded in MSB order. (0x00000000 if master key)
    var index = buffer.readUInt32BE(9)
    assert(depth > 0 || index === 0, 'Invalid index')
  
    // 32 bytes: the chain code
    var chainCode = buffer.slice(13, 45)
    var hd
  
    // 33 bytes: private key data (0x00 + k)
    if (params.isPrivate) {
      assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key')
      var data = buffer.slice(46, 78)
      var d = BigInteger.fromBuffer(data)
      hd = new HDNode(d, chainCode, params.network)
  
    // 33 bytes: public key data (0x02 + X or 0x03 + X)
    } else {
      var data = buffer.slice(45, 78)
      var Q = ecurve.Point.decodeFrom(curve, data)
      assert.equal(Q.compressed, true, 'Invalid public key')
  
      // Verify that the X coordinate in the public point corresponds to a point on the curve.
      // If not, the extended public key is invalid.
      curve.validate(Q)
  
      hd = new HDNode(Q, chainCode, params.network)
    }
  
    hd.depth = depth
    hd.index = index
    hd.parentFingerprint = parentFingerprint
  
    return hd
  }
  
  HDNode.fromHex = function(hex) {
    return HDNode.fromBuffer(new Buffer(hex, 'hex'))
  }
  
  HDNode.prototype.getIdentifier = function() {
    return crypto.hash160(this.pubKey.toBuffer())
  }
  
  HDNode.prototype.getFingerprint = function() {
    return this.getIdentifier().slice(0, 4)
  }
  
  HDNode.prototype.getAddress = function() {
    return this.pubKey.getAddress(this.network)
  }
  
  HDNode.prototype.neutered = function() {
    var neutered = new HDNode(this.pubKey.Q, this.chainCode, this.network)
    neutered.depth = this.depth
    neutered.index = this.index
    neutered.parentFingerprint = this.parentFingerprint
  
    return neutered
  }
  
  HDNode.prototype.toBase58 = function(isPrivate) {
    return base58check.encode(this.toBuffer(isPrivate))
  }
  
  HDNode.prototype.toBuffer = function(isPrivate) {
    if (isPrivate == undefined) {
      isPrivate = !!this.privKey
  
    // FIXME: remove in 2.x.y
    } else {
      console.warn('isPrivate flag is deprecated, please use the .neutered() method instead')
    }
  
    // Version
    var version = isPrivate ? this.network.bip32.private : this.network.bip32.public
    var buffer = new Buffer(HDNode.LENGTH)
  
    // 4 bytes: version bytes
    buffer.writeUInt32BE(version, 0)
  
    // Depth
    // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
    buffer.writeUInt8(this.depth, 4)
  
    // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
    var fingerprint = (this.depth === 0) ? 0x00000000 : this.parentFingerprint
    buffer.writeUInt32BE(fingerprint, 5)
  
    // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
    // This is encoded in Big endian. (0x00000000 if master key)
    buffer.writeUInt32BE(this.index, 9)
  
    // 32 bytes: the chain code
    this.chainCode.copy(buffer, 13)
  
    // 33 bytes: the public key or private key data
    if (isPrivate) {
      // FIXME: remove in 2.x.y
      assert(this.privKey, 'Missing private key')
  
      // 0x00 + k for private keys
      buffer.writeUInt8(0, 45)
      this.privKey.d.toBuffer(32).copy(buffer, 46)
    } else {
  
      // X9.62 encoding for public keys
      this.pubKey.toBuffer().copy(buffer, 45)
    }
  
    return buffer
  }
  
  HDNode.prototype.toHex = function(isPrivate) {
    return this.toBuffer(isPrivate).toString('hex')
  }
  
  // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
  HDNode.prototype.derive = function(index) {
    var isHardened = index >= HDNode.HIGHEST_BIT
    var indexBuffer = new Buffer(4)
    indexBuffer.writeUInt32BE(index, 0)
  
    var data
  
    // Hardened child
    if (isHardened) {
      assert(this.privKey, 'Could not derive hardened child key')
  
      // data = 0x00 || ser256(kpar) || ser32(index)
      data = Buffer.concat([
        this.privKey.d.toBuffer(33),
        indexBuffer
      ])
  
    // Normal child
    } else {
      // data = serP(point(kpar)) || ser32(index)
      //      = serP(Kpar) || ser32(index)
      data = Buffer.concat([
        this.pubKey.toBuffer(),
        indexBuffer
      ])
    }
  
    var I = crypto.HmacSHA512(data, this.chainCode)
    var IL = I.slice(0, 32)
    var IR = I.slice(32)
  
    var pIL = BigInteger.fromBuffer(IL)
  
    // In case parse256(IL) >= n, proceed with the next value for i
    if (pIL.compareTo(curve.n) >= 0) {
      return this.derive(index + 1)
    }
  
    // Private parent key -> private child key
    var hd
    if (this.privKey) {
      // ki = parse256(IL) + kpar (mod n)
      var ki = pIL.add(this.privKey.d).mod(curve.n)
  
      // In case ki == 0, proceed with the next value for i
      if (ki.signum() === 0) {
        return this.derive(index + 1)
      }
  
      hd = new HDNode(ki, IR, this.network)
  
    // Public parent key -> public child key
    } else {
      // Ki = point(parse256(IL)) + Kpar
      //    = G*IL + Kpar
      var Ki = curve.G.multiply(pIL).add(this.pubKey.Q)
  
      // In case Ki is the point at infinity, proceed with the next value for i
      if (curve.isInfinity(Ki)) {
        return this.derive(index + 1)
      }
  
      hd = new HDNode(Ki, IR, this.network)
    }
  
    hd.depth = this.depth + 1
    hd.index = index
    hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
  
    return hd
  }
  
  HDNode.prototype.deriveHardened = function(index) {
    // Only derives hardened private keys by default
    return this.derive(index + HDNode.HIGHEST_BIT)
  }
  
  HDNode.prototype.toString = HDNode.prototype.toBase58
  
  module.exports = HDNode
  