draft completion

This commit is contained in:
Phillip Lang Martinez 2024-07-15 22:07:57 -04:00
parent 62aed9fea2
commit f6c0afbc40
3 changed files with 376 additions and 304 deletions

View File

@ -216,5 +216,13 @@ chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
type: "LOGOUT", type: "LOGOUT",
from: 'qortal' from: 'qortal'
}, "*"); }, "*");
} } else if (message.type === "RESPONSE_FOR_TRADES") {
// Notify the web page
window.postMessage({
type: "RESPONSE_FOR_TRADES",
from: 'qortal',
payload: message.message
}, "*");
}
}); });

View File

@ -22,6 +22,9 @@ const apiEndpoints = [
"https://apinode4.qortalnodes.live", "https://apinode4.qortalnodes.live",
]; ];
const buyTradeNodeBaseUrl = 'https://appnode.qortal.org'
const proxyAccountAddress = 'QXPejUe5Za1KD3zCMViWCX35AreMQ9H7ku'
const proxyAccountPublicKey = '5hP6stDWybojoDw5t8z9D51nV945oMPX7qBd29rhX1G7'
const pendingResponses = new Map(); const pendingResponses = new Map();
// Function to check each API endpoint // Function to check each API endpoint
@ -109,9 +112,8 @@ async function connection(hostname) {
} }
async function getTradeInfo(qortalAtAddress) { async function getTradeInfo(qortalAtAddress) {
const validApi = await findUsableApi(); const response = await fetch(buyTradeNodeBaseUrl + "/crosschain/trade/" + qortalAtAddress);
const response = await fetch(validApi + "/crosschain/trade/" + qortalAtAddress); console.log({})
if (!response?.ok) throw new Error("Cannot crosschain trade information"); if (!response?.ok) throw new Error("Cannot crosschain trade information");
const data = await response.json(); const data = await response.json();
return data; return data;
@ -253,7 +255,7 @@ async function getNameOrAddress(receiver) {
} }
} }
async function decryptWallet({password, wallet, walletVersion}) { async function decryptWallet({ password, wallet, walletVersion }) {
try { try {
const response = await decryptStoredWallet(password, wallet); const response = await decryptStoredWallet(password, wallet);
const wallet2 = new PhraseWallet(response, walletVersion); const wallet2 = new PhraseWallet(response, walletVersion);
@ -290,12 +292,13 @@ async function decryptWallet({password, wallet, walletVersion}) {
return true; return true;
} catch (error) { } catch (error) {
console.log({error}) console.log({ error })
throw new Error(error.message); throw new Error(error.message);
} }
} }
async function signChatFunc(chatBytesArray, chatNonce, validApi, keyPair ){ async function signChatFunc(chatBytesArray, chatNonce, validApi, keyPair) {
console.log({ chatBytesArray, chatNonce, validApi, keyPair })
let response let response
try { try {
const signedChatBytes = signChat( const signedChatBytes = signChat(
@ -320,7 +323,7 @@ function sbrk(size, heap) {
return old return old
} }
const computePow = async ({chatBytes, path, difficulty}) => { const computePow = async ({ chatBytes, path, difficulty }) => {
let response = null let response = null
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
const _chatBytesArray = Object.keys(chatBytes).map(function (key) { const _chatBytesArray = Object.keys(chatBytes).map(function (key) {
@ -329,7 +332,7 @@ const computePow = async ({chatBytes, path, difficulty}) => {
const chatBytesArray = new Uint8Array(_chatBytesArray) const chatBytesArray = new Uint8Array(_chatBytesArray)
const chatBytesHash = new Sha256().process(chatBytesArray).finish().result const chatBytesHash = new Sha256().process(chatBytesArray).finish().result
const memory = new WebAssembly.Memory({ initial: 256, maximum: 256 }) const memory = new WebAssembly.Memory({ initial: 256, maximum: 256 })
const heap = new Uint8Array(memory.buffer) const heap = new Uint8Array(memory.buffer)
const hashPtr = sbrk(32, heap) const hashPtr = sbrk(32, heap)
const hashAry = new Uint8Array(memory.buffer, hashPtr, 32) const hashAry = new Uint8Array(memory.buffer, hashPtr, 32)
@ -359,7 +362,7 @@ const heap = new Uint8Array(memory.buffer)
return response return response
} }
async function sendChat({qortAddress, recipientPublicKey, message }){ async function sendChat({ qortAddress, recipientPublicKey, message }) {
let _reference = new Uint8Array(64); let _reference = new Uint8Array(64);
self.crypto.getRandomValues(_reference); self.crypto.getRandomValues(_reference);
@ -376,15 +379,17 @@ async function sendChat({qortAddress, recipientPublicKey, message }){
publicKey: uint8PublicKey publicKey: uint8PublicKey
}; };
const difficulty = 8; const difficulty = 8;
const callRequest = `curl -X 'POST' 'http://localhost:12391/crosschain/tradebot/respond' -H 'accept: text/plain' -H 'X-API-KEY: keykeykeykey' -H 'Content-Type: application/json' -d '{ "atAddress": "${message.atAddress}", "foreignKey": "${message.foreignKey}", "receivingAddress": "${message.receivingAddress}" }'`; const jsonData = {
atAddress: message.atAddress,
// Construct the final JSON object foreignKey: message.foreignKey,
const finalJson = { receivingAddress: message.receivingAddress
callRequest: callRequest, };
const finalJson = {
callRequest: jsonData,
extra: "whatever additional data goes here" extra: "whatever additional data goes here"
}; };
const messageStringified = JSON.stringify(finalJson) const messageStringified = JSON.stringify(finalJson)
const {chatBytes} = await createTransaction( const { chatBytes } = await createTransaction(
18, 18,
keyPair, keyPair,
{ {
@ -405,14 +410,17 @@ const finalJson = {
const {nonce, chatBytesArray} = await computePow({ chatBytes, path, difficulty }) const { nonce, chatBytesArray } = await computePow({ chatBytes, path, difficulty })
let _response = await signChatFunc(chatBytesArray, let _response = await signChatFunc(chatBytesArray,
nonce, "https://appnode.qortal.org", keyPair nonce, "https://appnode.qortal.org", keyPair
) )
if (_response?.error) {
throw new Error(_response?.message)
}
return _response return _response
} }
async function createBuyOrderTx({crosschainAtInfo}){ async function createBuyOrderTx({ crosschainAtInfo }) {
try { try {
const wallet = await getSaveWallet(); const wallet = await getSaveWallet();
const address = wallet.address0; const address = wallet.address0;
@ -424,16 +432,17 @@ async function createBuyOrderTx({crosschainAtInfo}){
foreignKey: parsedData.ltcPrivateKey, foreignKey: parsedData.ltcPrivateKey,
receivingAddress: address receivingAddress: address
} }
const res = await sendChat({qortAddress: "QXPejUe5Za1KD3zCMViWCX35AreMQ9H7ku", recipientPublicKey: "5hP6stDWybojoDw5t8z9D51nV945oMPX7qBd29rhX1G7", message }) const res = await sendChat({ qortAddress: proxyAccountAddress, recipientPublicKey: proxyAccountPublicKey, message })
if(res?.signature){ if (res?.signature) {
const decryptedMessage = await listenForChatMessageForBuyOrder({
nodeBaseUrl: "https://appnode.qortal.org", listenForChatMessageForBuyOrder({
senderAddress: "QXPejUe5Za1KD3zCMViWCX35AreMQ9H7ku", nodeBaseUrl: buyTradeNodeBaseUrl,
senderPublicKey: "5hP6stDWybojoDw5t8z9D51nV945oMPX7qBd29rhX1G7", senderAddress: proxyAccountAddress,
senderPublicKey: proxyAccountPublicKey,
signature: res?.signature, signature: res?.signature,
}) })
return decryptedMessage return { atAddress: crosschainAtInfo.qortalAtAddress, chatSignature: res?.signature, node: buyTradeNodeBaseUrl }
} }
} catch (error) { } catch (error) {
@ -448,7 +457,7 @@ async function sendCoin({ password, amount, receiver }, skipConfirmPassword) {
throw new Error("Invalid receiver address or name"); throw new Error("Invalid receiver address or name");
const wallet = await getSaveWallet(); const wallet = await getSaveWallet();
let keyPair = '' let keyPair = ''
if(skipConfirmPassword){ if (skipConfirmPassword) {
const resKeyPair = await getKeyPair() const resKeyPair = await getKeyPair()
const parsedData = JSON.parse(resKeyPair) const parsedData = JSON.parse(resKeyPair)
const uint8PrivateKey = Base58.decode(parsedData.privateKey); const uint8PrivateKey = Base58.decode(parsedData.privateKey);
@ -513,6 +522,58 @@ function fetchMessages(apiCall) {
}); });
} }
function fetchMessagesForBuyOrders(apiCall, signature, senderPublicKey) {
let retryDelay = 2000; // Start with a 2-second delay
const maxDuration = 360000 * 2; // Maximum duration set to 12 minutes
const startTime = Date.now(); // Record the start time
let triedChatMessage = []
// Promise to handle polling logic
return new Promise((resolve, reject) => {
const attemptFetch = async () => {
if (Date.now() - startTime > maxDuration) {
return reject(new Error("Maximum polling time exceeded"));
}
try {
const response = await fetch(apiCall);
let data = await response.json();
data = data.filter((item) => !triedChatMessage.includes(item.signature))
console.log({data})
if (data && data.length > 0) {
const encodedMessageObj = data[0]
const resKeyPair = await getKeyPair()
const parsedData = JSON.parse(resKeyPair)
const uint8PrivateKey = Base58.decode(parsedData.privateKey);
const uint8PublicKey = Base58.decode(parsedData.publicKey);
const keyPair = {
privateKey: uint8PrivateKey,
publicKey: uint8PublicKey
};
const decodedMessage = decryptChatMessage(encodedMessageObj.data, keyPair.privateKey, senderPublicKey, encodedMessageObj.reference)
const parsedMessage = JSON.parse(decodedMessage)
console.log({parsedMessage})
if (parsedMessage?.extra?.chatRequestSignature === signature) {
resolve(parsedMessage);
} else {
triedChatMessage.push(encodedMessageObj.signature)
setTimeout(attemptFetch, retryDelay);
retryDelay = Math.min(retryDelay * 2, 360000); // Ensure delay does not exceed 6 minutes
}
// Resolve the promise when data is found
} else {
setTimeout(attemptFetch, retryDelay);
retryDelay = Math.min(retryDelay * 2, 360000); // Ensure delay does not exceed 6 minutes
}
} catch (error) {
reject(error); // Reject the promise on error
}
};
attemptFetch(); // Initial call to start the polling
});
}
async function listenForChatMessage({ nodeBaseUrl, senderAddress, senderPublicKey, timestamp }) { async function listenForChatMessage({ nodeBaseUrl, senderAddress, senderPublicKey, timestamp }) {
try { try {
let validApi = ""; let validApi = "";
@ -564,20 +625,24 @@ async function listenForChatMessageForBuyOrder({ nodeBaseUrl, senderAddress, sen
const before = Date.now() + 1200000 const before = Date.now() + 1200000
const after = Date.now() const after = Date.now()
const apiCall = `${validApi}/chat/messages?involving=${senderAddress}&involving=${address}&reverse=true&limit=1&before=${before}&after=${after}`; const apiCall = `${validApi}/chat/messages?involving=${senderAddress}&involving=${address}&reverse=true&limit=1&before=${before}&after=${after}`;
const encodedMessageObj = await fetchMessages(apiCall) const parsedMessageObj = await fetchMessagesForBuyOrders(apiCall, signature, senderPublicKey)
const resKeyPair = await getKeyPair() // const resKeyPair = await getKeyPair()
const parsedData = JSON.parse(resKeyPair) // const parsedData = JSON.parse(resKeyPair)
const uint8PrivateKey = Base58.decode(parsedData.privateKey); // const uint8PrivateKey = Base58.decode(parsedData.privateKey);
const uint8PublicKey = Base58.decode(parsedData.publicKey); // const uint8PublicKey = Base58.decode(parsedData.publicKey);
const keyPair = { // const keyPair = {
privateKey: uint8PrivateKey, // privateKey: uint8PrivateKey,
publicKey: uint8PublicKey // publicKey: uint8PublicKey
}; // };
const decodedMessage = decryptChatMessage(encodedMessageObj.data, keyPair.privateKey, senderPublicKey, encodedMessageObj.reference) // const decodedMessage = decryptChatMessage(encodedMessageObj.data, keyPair.privateKey, senderPublicKey, encodedMessageObj.reference)
const parsedMessage = JSON.parse(decodedMessage) // const parsedMessage = JSON.parse(decodedMessage)
return parsedMessage chrome.tabs.query({}, function (tabs) {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, { type: "RESPONSE_FOR_TRADES", message: parsedMessageObj });
});
});
} catch (error) { } catch (error) {
console.error(error) console.error(error)
throw new Error(error.message); throw new Error(error.message);
@ -602,7 +667,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
break; break;
case "getWalletInfo": case "getWalletInfo":
getKeyPair().then(()=> { getKeyPair().then(() => {
chrome.storage.local.get(["walletInfo"], (result) => { chrome.storage.local.get(["walletInfo"], (result) => {
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
sendResponse({ error: chrome.runtime.lastError.message }); sendResponse({ error: chrome.runtime.lastError.message });
@ -612,7 +677,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
sendResponse({ error: "No wallet info found" }); sendResponse({ error: "No wallet info found" });
} }
}); });
}).catch((error)=> { }).catch((error) => {
sendResponse({ error: error.message }); sendResponse({ error: error.message });
}) })
@ -1134,7 +1199,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// Handle error // Handle error
console.error(chrome.runtime.lastError.message); console.error(chrome.runtime.lastError.message);
} else { } else {
chrome.tabs.query({}, function(tabs) { chrome.tabs.query({}, function (tabs) {
tabs.forEach(tab => { tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, { type: "LOGOUT" }); chrome.tabs.sendMessage(tab.id, { type: "LOGOUT" });
}); });

View File

@ -4,7 +4,6 @@ import nacl from '../deps/nacl-fast'
import utils from '../utils/utils' import utils from '../utils/utils'
export const signChat = (chatBytes, nonce, keyPair) => { export const signChat = (chatBytes, nonce, keyPair) => {
if (!chatBytes) { if (!chatBytes) {
throw new Error('Chat Bytes not defined') throw new Error('Chat Bytes not defined')
} }