From 67204771a27a831bc514d26fe38afb4150528833 Mon Sep 17 00:00:00 2001 From: kent-3 <100624004+kent-3@users.noreply.github.com> Date: Thu, 29 Aug 2024 15:40:23 -0400 Subject: [PATCH] integration test fixes --- TNLS-Gateways/secret/tests/integration.ts | 212 +++++++++++++--------- 1 file changed, 131 insertions(+), 81 deletions(-) diff --git a/TNLS-Gateways/secret/tests/integration.ts b/TNLS-Gateways/secret/tests/integration.ts index 7707ae5..aec8ed6 100644 --- a/TNLS-Gateways/secret/tests/integration.ts +++ b/TNLS-Gateways/secret/tests/integration.ts @@ -5,11 +5,19 @@ import assert from "assert"; import { PreExecutionMsg, Payload, Binary } from "./GatewayContract"; import { ecdsaSign, publicKeyConvert } from "secp256k1"; import { Wallet as EthWallet } from "ethers"; -import { arrayify, hexlify, SigningKey, computeAddress, recoverAddress, recoverPublicKey, keccak256 } from "ethers/lib/utils"; +import { + arrayify, + hexlify, + SigningKey, + computeAddress, + recoverAddress, + recoverPublicKey, + keccak256, +} from "ethers/lib/utils"; import sha3 from "js-sha3"; -import { createHash, randomBytes } from 'crypto'; -import { encrypt_payload } from './encrypt-payload/pkg' -import 'dotenv/config' +import { createHash, randomBytes } from "crypto"; +import { encrypt_payload } from "./encrypt-payload/pkg"; +import "dotenv/config"; var mnemonic: string; var endpoint: string = "http://localhost:1317"; @@ -43,26 +51,26 @@ const initializeClient = async (endpoint: string, chainId: string) => { const initializeGateway = async ( client: SecretNetworkClient, - contractPath: string + contractPath: string, ) => { const wasmCode = fs.readFileSync(contractPath); console.log("\nUploading gateway contract"); const uploadReceipt = await client.tx.compute.storeCode( { - wasmByteCode: wasmCode, + wasm_byte_code: wasmCode, sender: client.address, source: "", builder: "", }, { gasLimit: 5000000, - } + }, ); if (uploadReceipt.code !== 0) { console.log( - `Failed to get code id: ${JSON.stringify(uploadReceipt.rawLog)}` + `Failed to get code id: ${JSON.stringify(uploadReceipt.rawLog)}`, ); throw new Error(`Failed to upload contract`); } @@ -70,7 +78,7 @@ const initializeGateway = async ( const codeIdKv = uploadReceipt.jsonLog![0].events[0].attributes.find( (a: any) => { return a.key === "code_id"; - } + }, ); console.log(`Upload used \x1b[33m${uploadReceipt.gasUsed}\x1b[0m gas\n`); @@ -78,36 +86,37 @@ const initializeGateway = async ( const codeId = Number(codeIdKv!.value); console.log("Contract codeId: ", codeId); - const contractCodeHash = await client.query.compute.codeHash(codeId); + const { code_hash: contractCodeHash } = + await client.query.compute.codeHashByCodeId({ code_id: codeId.toString() }); console.log(`Contract hash: ${contractCodeHash}`); const contract = await client.tx.compute.instantiateContract( { sender: client.address, - codeId, - initMsg: {}, - codeHash: contractCodeHash, + code_id: codeId, + init_msg: {}, + code_hash: contractCodeHash, label: "My contract" + Math.ceil(Math.random() * 10000), // The label should be unique for every contract, add random string in order to maintain uniqueness }, { gasLimit: 5000000, - } + }, ); if (contract.code !== 0) { throw new Error( - `Failed to instantiate the contract with the following error ${contract.rawLog}` + `Failed to instantiate the contract with the following error ${contract.rawLog}`, ); } const contractAddress = contract.arrayLog!.find( - (log) => log.type === "message" && log.key === "contract_address" + (log) => log.type === "message" && log.key === "contract_address", )!.value; console.log(`Contract address: ${contractAddress}\n`); console.log(`Init used \x1b[33m${contract.gasUsed}\x1b[0m gas\n`); - var gatewayInfo: [string, string] = [contractCodeHash, contractAddress]; + var gatewayInfo: [string, string] = [contractCodeHash!, contractAddress]; return gatewayInfo; }; @@ -130,12 +139,12 @@ const initializeContract = async ( }, { gasLimit: 5000000, - } + }, ); if (uploadReceipt.code !== 0) { console.log( - `Failed to get code id: ${JSON.stringify(uploadReceipt.rawLog)}` + `Failed to get code id: ${JSON.stringify(uploadReceipt.rawLog)}`, ); throw new Error(`Failed to upload contract`); } @@ -143,7 +152,7 @@ const initializeContract = async ( const codeIdKv = uploadReceipt.jsonLog![0].events[0].attributes.find( (a: any) => { return a.key === "code_id"; - } + }, ); console.log(`Upload used \x1b[33m${uploadReceipt.gasUsed}\x1b[0m gas\n`); @@ -151,7 +160,9 @@ const initializeContract = async ( const codeId = codeIdKv!.value; console.log("Contract codeId: ", codeId); - const contractCodeHash = await client.query.compute.codeHashByCodeId({code_id: codeId}); + const contractCodeHash = await client.query.compute.codeHashByCodeId({ + code_id: codeId, + }); console.log(`Contract hash: ${contractCodeHash}`); const contract = await client.tx.compute.instantiateContract( @@ -168,24 +179,27 @@ const initializeContract = async ( }, { gasLimit: 5000000, - } + }, ); if (contract.code !== 0) { throw new Error( - `Failed to instantiate the contract with the following error ${contract.rawLog}` + `Failed to instantiate the contract with the following error ${contract.rawLog}`, ); } const contractAddress = contract.arrayLog!.find( - (log) => log.type === "message" && log.key === "contract_address" + (log) => log.type === "message" && log.key === "contract_address", )!.value; console.log(`Contract address: ${contractAddress}\n`); console.log(`Init used \x1b[33m${contract.gasUsed}\x1b[0m gas`); - var gatewayInfo: [string, string] = [contractCodeHash, contractAddress]; + var gatewayInfo: [string, string] = [ + contractCodeHash.code_hash!, + contractAddress, + ]; return gatewayInfo; }; @@ -198,15 +212,15 @@ async function getScrtBalance(userCli: SecretNetworkClient): Promise { address: userCli.address, denom: "uscrt", }); - return balanceResponse.balance!.amount; + return balanceResponse.balance!.amount!; } async function fillUpFromFaucet( client: SecretNetworkClient, - targetBalance: Number + targetBalance: Number, ) { let balance = await getScrtBalance(client); - while (Number(balance) < targetBalance) { + while (Number(balance) < Number(targetBalance)) { try { await getFromFaucet(client.address); } catch (e) { @@ -219,11 +233,12 @@ async function fillUpFromFaucet( // Initialization procedure async function initializeAndUploadContract() { - const client = await initializeClient(endpoint, chainId); - if (chainId == "secretdev-1") {await fillUpFromFaucet(client, 100_000_000)}; - + if (chainId == "secretdev-1") { + await fillUpFromFaucet(client, 100_000_000); + } + const [gatewayHash, gatewayAddress] = await initializeGateway( client, "../../TNLS-Gateways/secret/contract.wasm.gz", @@ -232,7 +247,10 @@ async function initializeAndUploadContract() { console.log(`Sending query: {"get_public_keys": {} }`); const gatewayKeys = await queryPubKey(client, gatewayHash, gatewayAddress); - const gatewayKey = Buffer.from(gatewayKeys.verification_key.substring(2), 'hex').toString('base64') + const gatewayKey = Buffer.from( + gatewayKeys.verification_key.substring(2), + "hex", + ).toString("base64"); const [contractHash, contractAddress] = await initializeContract( client, @@ -242,7 +260,7 @@ async function initializeAndUploadContract() { gatewayKey, ); - var clientInfo: [SecretNetworkClient, string, string, string, string, string, string] = [ + var clientInfo: [SecretNetworkClient, string, string, string, string] = [ client, gatewayHash, gatewayAddress, @@ -260,46 +278,59 @@ async function gatewayTx( contractAddress: string, gatewayPublicKey: string, // base64, encryption key ) { - const wallet = EthWallet.createRandom(); + const wallet = EthWallet.createRandom(); const userPublicAddress: string = wallet.address; - const userPublicKey: string = new SigningKey(wallet.privateKey).compressedPublicKey; + const userPublicKey: string = new SigningKey(wallet.privateKey) + .compressedPublicKey; // console.log(`\n\x1b[34mEthereum Address: ${wallet.address}\n\x1b[34mPublic Key: ${userPublicKey}\n\x1b[34mPrivate Key: ${wallet.privateKey}\x1b[0m\n`); - const userPrivateKeyBytes = arrayify(wallet.privateKey) - const userPublicKeyBytes = arrayify(userPublicKey) - const gatewayPublicKeyBuffer = Buffer.from(gatewayPublicKey, 'base64') - const gatewayPublicKeyBytes = arrayify(gatewayPublicKeyBuffer) - - const inputs = JSON.stringify({"my_value": 1}); + const userPrivateKeyBytes = arrayify(wallet.privateKey); + const userPublicKeyBytes = arrayify(userPublicKey); + const gatewayPublicKeyBuffer = Buffer.from(gatewayPublicKey, "base64"); + const gatewayPublicKeyBytes = arrayify(gatewayPublicKeyBuffer); + + const inputs = JSON.stringify({ my_value: 1 }); const routing_info = contractAddress; const routing_code_hash = contractHash; const user_address = userPublicAddress; - const user_key = Buffer.from(userPublicKeyBytes).toString('base64'); + const user_key = Buffer.from(userPublicKeyBytes).toString("base64"); const payload: Payload = { data: inputs, routing_info: routing_info, routing_code_hash: routing_code_hash, user_address: user_address, - user_key: user_key + user_key: user_key, }; console.log("Unencrypted Payload:"); console.log(payload); - const plaintext = Buffer - .from(JSON.stringify(payload)); + const plaintext = Buffer.from(JSON.stringify(payload)); const nonce = arrayify(randomBytes(12)); - let ciphertext = Buffer - .from(encrypt_payload(gatewayPublicKeyBytes, userPrivateKeyBytes, plaintext, nonce)) - .toString('base64'); - - const payloadHash = createHash('sha256').update(ciphertext,'base64').digest(); + let ciphertext = Buffer.from( + encrypt_payload( + gatewayPublicKeyBytes, + userPrivateKeyBytes, + plaintext, + nonce, + ), + ).toString("base64"); + + const payloadHash = createHash("sha256") + .update(ciphertext, "base64") + .digest(); // const payloadHash64 = payloadHash.toString('base64'); - const payloadSignature = ecdsaSign(payloadHash, userPrivateKeyBytes).signature; + const payloadSignature = ecdsaSign( + payloadHash, + userPrivateKeyBytes, + ).signature; // const payloadSignature64 = Buffer.from(payloadSignature).toString('base64'); - const user_pubkey = publicKeyConvert(arrayify(recoverPublicKey(arrayify(payloadHash), payloadSignature)),true) - console.log(`Recovered user_pubkey: ${hexlify(user_pubkey)}`) + const user_pubkey = publicKeyConvert( + arrayify(recoverPublicKey(arrayify(payloadHash), payloadSignature)), + true, + ); + console.log(`Recovered user_pubkey: ${hexlify(user_pubkey)}`); const handle_msg: PreExecutionMsg = { task_id: 1, @@ -308,11 +339,11 @@ async function gatewayTx( routing_code_hash: routing_code_hash, user_address: user_address, user_key: user_key, - user_pubkey: Buffer.from(user_pubkey).toString('base64'), + user_pubkey: Buffer.from(user_pubkey).toString("base64"), payload: ciphertext, - nonce: Buffer.from(nonce).toString('base64'), - payload_hash: payloadHash.toString('base64'), - payload_signature: Buffer.from(payloadSignature).toString('base64'), + nonce: Buffer.from(nonce).toString("base64"), + payload_hash: payloadHash.toString("base64"), + payload_signature: Buffer.from(payloadSignature).toString("base64"), source_network: "ethereum", }; console.log("handle_msg:"); @@ -330,21 +361,19 @@ async function gatewayTx( }, { gasLimit: 500000, - } + }, ); if (tx.code !== 0) { - throw new Error( - `Failed with the following error:\n ${tx.rawLog}` - ); - }; + throw new Error(`Failed with the following error:\n ${tx.rawLog}`); + } // Parsing the logs from the 'Output' handle - let logs: {[index: string]:string} = {}; + let logs: { [index: string]: string } = {}; const logKeys = [ "source_network", "task_destination_network", - "task_id", + "task_id", "payload_hash", "result", "result_hash", @@ -353,19 +382,22 @@ async function gatewayTx( "packet_signature", ]; - logKeys.forEach((key) => logs[key] = tx.arrayLog!.find( - (log) => log.type === "wasm" && log.key === key - )!.value); + logKeys.forEach( + (key) => + (logs[key] = tx.arrayLog!.find( + (log) => log.type === "wasm" && log.key === key, + )!.value), + ); console.log("\nOutput Logs:"); console.log(logs); - console.log('\nTesting recoverAddress on each signature:') + console.log("\nTesting recoverAddress on each signature:"); // const test1 = recoverAddress(logs["payload_hash"], logs["payload_signature"]); const test2 = recoverAddress(logs["result_hash"], logs["result_signature"]); const test3 = recoverAddress(logs["packet_hash"], logs["packet_signature"]); - [test2, test3].forEach(element => { - console.log(element) + [test2, test3].forEach((element) => { + console.log(element); }); assert(logs["source_network"] == "secret"); @@ -381,14 +413,13 @@ async function gatewayTx( console.log(`inputTx used \x1b[33m${tx.gasUsed}\x1b[0m gas`); } -type PublicKeyResponse = { encryption_key: Binary, verification_key: Binary }; +type PublicKeyResponse = { encryption_key: Binary; verification_key: Binary }; async function queryPubKey( client: SecretNetworkClient, gatewayHash: string, gatewayAddress: string, ): Promise { - const response = (await client.query.compute.queryContract({ contract_address: gatewayAddress, code_hash: gatewayHash, @@ -397,9 +428,11 @@ async function queryPubKey( console.log(`\x1b[32mEncryption key: ${response.encryption_key}\x1b[0m`); console.log(`\x1b[32mPublic key: ${response.verification_key}\x1b[0m`); - console.log(`\x1b[34;1mEth Address: ${computeAddress(response.verification_key)}\x1b[0m`); + console.log( + `\x1b[34;1mEth Address: ${computeAddress(response.verification_key)}\x1b[0m`, + ); - return response + return response; } async function test_gateway_tx( @@ -410,8 +443,19 @@ async function test_gateway_tx( contractAddress: string, ) { console.log(`Sending query: {"get_public_keys": {} }`); - const gatewayPublicKey = await queryPubKey(client, gatewayHash, gatewayAddress); - await gatewayTx(client, gatewayHash, gatewayAddress, contractHash, contractAddress, gatewayPublicKey.encryption_key); + const gatewayPublicKey = await queryPubKey( + client, + gatewayHash, + gatewayAddress, + ); + await gatewayTx( + client, + gatewayHash, + gatewayAddress, + contractHash, + contractAddress, + gatewayPublicKey.encryption_key, + ); } async function runTestFunction( @@ -429,7 +473,13 @@ async function runTestFunction( contractAddress: string, ) { console.log(`\n[ \x1b[35mTEST\x1b[0m ] ${tester.name}\n`); - await tester(client, gatewayHash, gatewayAddress, contractHash, contractAddress); + await tester( + client, + gatewayHash, + gatewayAddress, + contractHash, + contractAddress, + ); console.log(`\n[ \x1b[32mOK\x1b[0m ] ${tester.name}\n`); } @@ -440,9 +490,9 @@ async function runTestFunction( await runTestFunction( test_gateway_tx, client, - gatewayHash, - gatewayAddress, - contractHash, - contractAddress + gatewayHash, + gatewayAddress, + contractHash, + contractAddress, ); })();