lib/ex_s_wallet.ex

defmodule ExSWallet do
  @moduledoc """
  Documentation for `ExSWallet`.
  """

  defp loadProtected() do
    %{
      alg: "PBES2-HS512",
      enc: "A256GCM",
      p2c: 4096,
      p2s: :crypto.strong_rand_bytes(32)
    }
  end

  defp encryptSecret(stellarSecret, password) do
    PBCS.encrypt({password, stellarSecret}, loadProtected(), password: password)
  end

  defp decryptSecret(encryptedStellarSecret, password) do
    PBCS.decrypt({password, encryptedStellarSecret}, password: password)
  end

  def loadSecret(walletName, password) do
    {:ok, text} = File.read("#{System.user_home!()}/.exswalletrc")
    decryptSecret(Map.get(Poison.decode!(text), walletName), password)
  end

  def walletSetup(walletName, stellarSecret, password) do
    {:ok, file} = File.open("#{System.user_home!()}/.exswalletrc", [:write])
    encryptedSecret = encryptSecret(stellarSecret, password)
    IO.binwrite(file, Poison.encode!(%{"#{walletName}" => "#{encryptedSecret}"}))
    File.close(file)
    :ok
  end

  def txSign(tx, walletName, password) do
    {:ok, secretKey} = loadSecret(walletName, password)
    signature = Stellar.KeyPair.from_secret_seed(secretKey)
    Stellar.TxBuild.TransactionEnvelope.to_base64(Stellar.TxBuild.TransactionEnvelope.add_signature(tx, Stellar.TxBuild.Signature.new(signature)))
  end
  
end