Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft] ad-hoc-processing #31

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 52 additions & 32 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
getTatumKey,
getQuestion
} from './management';
import { processSignatures } from './signatures';
import { processSignatures, processSignaturesAsDaemon } from './signatures';
import http from 'http';
import https from 'https';
import meow from 'meow';
Expand Down Expand Up @@ -82,44 +82,64 @@ const { input: command, flags } = meow(`
}
}
});

const getPwd = async (source: "AZURE" | "VGS" | "PWD") => {
if (source == 'AZURE') {
const vaultUrl = config.getValue(ConfigOption.AZURE_VAULTURL);
const secretName = config.getValue(ConfigOption.AZURE_SECRETNAME);
const secretVersion = config.getValue(ConfigOption.AZURE_SECRETVERSION);
const pwd = (await axiosInstance.get(`https://${vaultUrl}/secrets/${secretName}/${secretVersion}?api-version=7.1`)).data?.data[0]?.value;
if (!pwd) {
console.error('Azure Vault secret does not exists.');
process.exit(-1);
return;
}
return pwd;

} else if (source == 'VGS') {
const username = config.getValue(ConfigOption.VGS_USERNAME);
const password = config.getValue(ConfigOption.VGS_PASSWORD);
const alias = config.getValue(ConfigOption.VGS_ALIAS);
const pwd = (await axiosInstance.get(`https://api.live.verygoodvault.com/aliases/${alias}`, {
auth: {
username,
password,
}
})).data?.data[0]?.value;
if (!pwd) {
console.error('VGS Vault alias does not exists.');
process.exit(-1);
return;
}
return pwd;
} else {
return config.getValue(ConfigOption.KMS_PASSWORD);
}
}

const startup = async () => {
if (command.length === 0) {
return;
}
const getPwdSource = () => {
if (flags.azure) {
return 'AZURE';
}
if (flags.vgs) {
return 'VGS';
}
return 'PWD';
}

switch (command[0]) {
case 'daemon':
let pwd = '';
if (flags.azure) {
const vaultUrl = config.getValue(ConfigOption.AZURE_VAULTURL);
const secretName = config.getValue(ConfigOption.AZURE_SECRETNAME);
const secretVersion = config.getValue(ConfigOption.AZURE_SECRETVERSION);
const pwd = (await axiosInstance.get(`https://${vaultUrl}/secrets/${secretName}/${secretVersion}?api-version=7.1`)).data?.data[0]?.value;
if (!pwd) {
console.error('Azure Vault secret does not exists.');
process.exit(-1);
return;
}

} else if (flags.vgs) {
const username = config.getValue(ConfigOption.VGS_USERNAME);
const password = config.getValue(ConfigOption.VGS_PASSWORD);
const alias = config.getValue(ConfigOption.VGS_ALIAS);
const pwd = (await axiosInstance.get(`https://api.live.verygoodvault.com/aliases/${alias}`, {
auth: {
username,
password,
}
})).data?.data[0]?.value;
if (!pwd) {
console.error('VGS Vault alias does not exists.');
process.exit(-1);
return;
}
} else {
pwd = config.getValue(ConfigOption.KMS_PASSWORD)
}
const daemonPwd = await getPwd(getPwdSource());
getTatumKey(flags.apiKey as string)
await processSignatures(pwd, flags.testnet, flags.period, axiosInstance, flags.path, flags.chain?.split(',') as Currency[], flags.externalUrl);
await processSignaturesAsDaemon(daemonPwd, flags.testnet, flags.period, axiosInstance, flags.path, flags.chain?.split(',') as Currency[], flags.externalUrl);
break;
case 'processsignatures':
const adHockPwd = await getPwd(getPwdSource());
await processSignatures(adHockPwd, flags.testnet, axiosInstance, flags.path, flags.chain?.split(',') as Currency[], flags.externalUrl);
break;
case 'generatewallet':
console.log(JSON.stringify(await generateWallet(command[1] as Currency, flags.testnet), null, 2));
Expand Down
121 changes: 72 additions & 49 deletions src/signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ import {
xlmBroadcast,
xrpBroadcast,
} from '@tatumio/tatum';
import {broadcast as kcsBroadcast, generatePrivateKeyFromMnemonic as kcsGeneratePrivateKeyFromMnemonic, signKMSTransaction as signKcsKMSTransaction} from '@tatumio/tatum-kcs'
import {broadcast as solanaBroadcast, signKMSTransaction as signSolanaKMSTransaction} from '@tatumio/tatum-solana';
import {TatumTerraSDK} from '@tatumio/terra'
import {AxiosInstance} from 'axios';
import {getManagedWallets, getWallet} from './management';
import { broadcast as kcsBroadcast, generatePrivateKeyFromMnemonic as kcsGeneratePrivateKeyFromMnemonic, signKMSTransaction as signKcsKMSTransaction } from '@tatumio/tatum-kcs'
import { broadcast as solanaBroadcast, signKMSTransaction as signSolanaKMSTransaction } from '@tatumio/tatum-solana';
import { TatumTerraSDK } from '@tatumio/terra'
import { AxiosInstance } from 'axios';
import { getManagedWallets, getWallet } from './management';

const processTransaction = async (
transaction: TransactionKMS,
Expand Down Expand Up @@ -132,7 +132,7 @@ const processTransaction = async (
);
return;
case Currency.LUNA:
const sdk = TatumTerraSDK({apiKey: process.env.TATUM_API_KEY as string})
const sdk = TatumTerraSDK({ apiKey: process.env.TATUM_API_KEY as string })
await sdk.blockchain.broadcast(
{
txData: await sdk.kms.sign(
Expand Down Expand Up @@ -461,7 +461,7 @@ const processTransaction = async (
});
};

export const processSignatures = async (
export const processSignaturesAsDaemon = (
pwd: string,
testnet: boolean,
period: number = 5,
Expand All @@ -470,7 +470,29 @@ export const processSignatures = async (
chains?: Currency[],
externalUrl?: string
) => {
let running = false;
return new Promise(function () {
let running = false;
setInterval(async () => {
if (running) {
return;
}
running = true;
await processSignatures(pwd, testnet, axios, path, chains, externalUrl)
running = false;
}, period * 1000);
})

}

export const processSignatures = async (
pwd: string,
testnet: boolean,
axios: AxiosInstance,
path?: string,
chains?: Currency[],
externalUrl?: string
) => {

const supportedChains = chains || [
Currency.BCH,
Currency.VET,
Expand All @@ -496,52 +518,53 @@ export const processSignatures = async (
Currency.ALGO,
Currency.KCS,
];
setInterval(async () => {
if (running) {
return;
}
running = true;

const transactions = [];
const transactions = [];

for (const supportedChain of supportedChains) {
try {
for (const supportedChain of supportedChains) {
const wallets = getManagedWallets(pwd, supportedChain, testnet, path).join(',');
console.log(
`${new Date().toISOString()} - Getting pending transaction from ${supportedChain} for wallets ${wallets}.`
);
transactions.push(
...(await getPendingTransactionsKMSByChain(supportedChain, wallets))
);
}
const wallets = getManagedWallets(pwd, supportedChain, testnet, path).join(',');
console.log(
`${new Date().toISOString()} - Getting pending transaction from ${supportedChain} for wallets ${wallets}.`
);
transactions.push(
...(await getPendingTransactionsKMSByChain(supportedChain, wallets))
);
} catch (e) {
console.error(e);
}
const data = [];
for (const transaction of transactions) {
try {
await processTransaction(transaction, testnet, pwd, axios, path, externalUrl);
} catch (e) {
const msg = e.response
? JSON.stringify(e.response.data, null, 2)
: `${e}`;
data.push({signatureId: transaction.id, error: msg});
console.error(`${new Date().toISOString()} - Could not process transaction id ${transaction.id}, error: ${msg}`);
}
}

const data = [];
for (const transaction of transactions) {
try {
await processTransaction(transaction, testnet, pwd, axios, path, externalUrl);
} catch (e) {
const msg = e.response
? JSON.stringify(e.response.data, null, 2)
: `${e}`;
data.push({ signatureId: transaction.id, error: msg });
console.error(`${new Date().toISOString()} - Could not process transaction id ${transaction.id}, error: ${msg}`);
}
if (data.length > 0) {
try {
const url = (process.env.TATUM_API_URL || 'https://api-eu1.tatum.io') +
'/v3/tatum/kms/batch';
await axios.post(
url,
{errors: data},
{headers: {'x-api-key': process.env.TATUM_API_KEY as string}}
);
console.log(`${new Date().toISOString()} - Send batch call to url '${url}'.`);
} catch (e) {
console.error(`${new Date().toISOString()} - Error received from API /v3/tatum/kms/batch - ${e.config.data}`);
}
}
if (data.length > 0) {
try {
const url = (process.env.TATUM_API_URL || 'https://api-eu1.tatum.io') +
'/v3/tatum/kms/batch';
await axios.post(
url,
{ errors: data },
{ headers: { 'x-api-key': process.env.TATUM_API_KEY as string } }
);
console.log(`${new Date().toISOString()} - Send batch call to url '${url}'.`);
} catch (e) {
console.error(`${new Date().toISOString()} - Error received from API /v3/tatum/kms/batch - ${e.config.data}`);
}
running = false;
}, period * 1000);
}


return {
transactions
}

};