const bip39 = require('bip39')  
const bip32 = require('bip32');  
const EC = require('elliptic').ec;  
  
json =`test json file`  
mnemonic = "簡 熙 夢 幾 聲 可 高 汪 煙 版 統 仇"  
path = "m/2018'/5'/1'/0/1"  
  
const sJWSinit = async () => {  
  console.log('-----sJWS Initial Start----- \n');  
  
  dkey = await DeriveKey(mnemonic, path)  
  console.log("\nGet dkey: %o \n", dkey)  
    
  console.log('\n-----elliptic ed25519 Start----- \n');  
  
  var EdDSA = require('elliptic').eddsa  
  var ec = new EdDSA('ed25519');  
  var eckeypair = ec.keyFromSecret(dkey.privateKey)  
    
  var privateKeyHex = new Buffer.from(eckeypair.getSecret()).toString('hex')  
  var publickeyHex = new Buffer.from(eckeypair.getPublic()).toString('hex')  
  console.log("private key hex: %o", privateKeyHex)  
  console.log("public key hex: %o\n", publickeyHex)  
  
  var signature = eckeypair.sign(json).toHex();  
  console.log("signature: %o\n", signature)  
  
  var ec2 = new EdDSA('ed25519');  
  var ec2keypair2 = ec2.keyFromPublic(publickeyHex, 'hex');  
  console.log("EdDSA json verify: %o", ec2keypair2.verify(json, signature));  
}  
  
(async () => {  
  console.log("--- aysnc sJWS init---")  
  await sJWSinit();  
})();  
  
async function DeriveKey(mnemonic, derivePath) {  
  if (bip39.validateMnemonic(mnemonic)) { console.log("mnemonic is fake!") }  
  
  return bip39.mnemonicToSeed(mnemonic).then((vseed)=>{  
    var root = bip32.fromSeed(vseed)  
    var PathNode = root.derivePath(derivePath)  
          
    console.log("# PATH 是 m/2018'/5'/1'/0/1/0  因為底下為derive(0),所以 path + '/0' \n")  
    console.log("privateKey (Hex): %o", PathNode.derive(0).privateKey.toString('hex'))  
    console.log("publicKey (Hex): %o", PathNode.derive(0).publicKey.toString('hex')) // 024ac10a81e3a0f86cb4dad68c6a26031d805a057f36048f80a5b91b1c2cb0588c 符合  
  
    return {  
      prv_buf: PathNode.derive(0).privateKey,  
      pub_buf: PathNode.derive(0).publicKey,  
      wif: PathNode.derive(0).toWIF(),  
      publicKey: PathNode.derive(0).publicKey.toString('hex'),  
      privateKey: PathNode.derive(0).privateKey.toString('hex'),  
      path: derivePath  
    }  
  }).catch((e) => {  
    console.error('handle error here: ', e.message)  
  })  
       
}