/********************************************************************************
 *   Ledger Node JS API
 *   (c) 2017-2018 Ledger
 *
 *  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.
 ********************************************************************************/
//@flow

import base32 from "base32.js";
import nacl from "tweetnacl";
import { sha256 } from "sha.js";

// TODO use bip32-path library
export function splitPath(path: string): number[] {
  let result = [];
  let components = path.split("/");
  components.forEach(element => {
    let number = parseInt(element, 10);
    if (isNaN(number)) {
      return; // FIXME shouldn't it throws instead?
    }
    if (element.length > 1 && element[element.length - 1] === "'") {
      number += 0x80000000;
    }
    result.push(number);
  });
  return result;
}

export function foreach<T, A>(
  arr: T[],
  callback: (T, number) => Promise<A>
): Promise<A[]> {
  function iterate(index, array, result) {
    if (index >= array.length) {
      return result;
    } else {
      return callback(array[index], index).then(function(res) {
        result.push(res);
        return iterate(index + 1, array, result);
      });
    }
  }
  return Promise.resolve().then(() => iterate(0, arr, []));
}

export function crc16xmodem(buf: Buffer, previous?: number): number {
  let crc = typeof previous !== "undefined" ? ~~previous : 0x0;

  for (var index = 0; index < buf.length; index++) {
    const byte = buf[index];
    let code = (crc >>> 8) & 0xff;

    code ^= byte & 0xff;
    code ^= code >>> 4;
    crc = (crc << 8) & 0xffff;
    crc ^= code;
    code = (code << 5) & 0xffff;
    crc ^= code;
    code = (code << 7) & 0xffff;
    crc ^= code;
  }

  return crc;
}

export function encodeEd25519PublicKey(rawPublicKey: Buffer): string {
  let versionByte = 6 << 3; // 'G'
  let data = Buffer.from(rawPublicKey);
  let versionBuffer = Buffer.from([versionByte]);
  let payload = Buffer.concat([versionBuffer, data]);
  let checksum = Buffer.alloc(2);
  checksum.writeUInt16LE(crc16xmodem(payload), 0);
  let unencoded = Buffer.concat([payload, checksum]);
  return base32.encode(unencoded);
}

export function verifyEd25519Signature(
  data: Buffer,
  signature: Buffer,
  publicKey: Buffer
): boolean {
  return nacl.sign.detached.verify(
    new Uint8Array(data.toJSON().data),
    new Uint8Array(signature.toJSON().data),
    new Uint8Array(publicKey.toJSON().data)
  );
}

export function hash(data: Buffer) {
  let hasher = new sha256();
  hasher.update(data, "utf8");
  return hasher.digest();
}

const knownStellarTechBIPs = [
  "148", // stellar.org
  "5248" // ficnetwork.com
];

export function checkStellarBip32Path(path: string): void {
  if (!knownStellarTechBIPs.some(bip => path.startsWith("44'/" + bip + "'"))) {
    throw new Error(
      "Not a BIP32 path of known networks using Stellar technology. Path: " +
        path +
        "." +
        " The Stellar app is authorized only for paths starting with " +
        knownStellarTechBIPs.map(bip => "44'/" + bip + "'").join(", ") +
        "." +
        " Example: 44'/148'/0'"
    );
  }
  path.split("/").forEach(function(element) {
    if (!element.toString().endsWith("'")) {
      throw new Error(
        "Detected a non-hardened path element in requested BIP32 path." +
          " Non-hardended paths are not supported at this time. Please use an all-hardened path." +
          " Example: 44'/148'/0'"
      );
    }
  });
}

@@ -3073,564 +3073,68 @@
 %0A%7D%0A%0A
-const knownStellarTechBIPs = %5B%0A  %22148%22, // stellar.org%0A  %225248%22 // ficnetwork.com%0A%5D;%0A%0Aexport function checkStellarBip32Path(path: string): void %7B%0A  if (!knownStellarTechBIPs.some(bip =%3E path.startsWith(%2244'/%22 + bip + %22'%22))) %7B%0A    throw new Error(%0A      %22Not a BIP32 path of known networks using Stellar technology. Path: %22 +%0A        path +%0A        %22.%22 +%0A        %22 The Stellar app is authorized only for paths starting with %22 +%0A        knownStellarTechBIPs.map(bip =%3E %2244'/%22 + bip + %22'%22).join(%22, %22) +%0A        %22.%22 +%0A        %22 Example: 44'/148'/0'%22%0A    );%0A  %7D
+export function checkStellarBip32Path(path: string): void %7B%0A
 %0A  p

Remove Stellar's 148 Bip32 check.