Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
SecretSaturn committed Jan 16, 2024
1 parent f9c054e commit 62a69cf
Show file tree
Hide file tree
Showing 15 changed files with 210 additions and 404 deletions.
2 changes: 1 addition & 1 deletion TNLS-Clients/VRFDemo/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
<div>
<h2>Sample Application: Roll the Dice!</h2>
<h2>Random Number Generation using Secret VRF, bridged into EVM.</h2>
<h3>This demo generates 2000 verifiable random numbers in just one transaction.</h3>
<h3>This demo generates 10 (can be up to 2000) verifiable random numbers in just one transaction.</h3>
<div id="form">
<button id="submit">Roll the dice </button>
<form name="inputForm">
Expand Down
16 changes: 9 additions & 7 deletions TNLS-Clients/VRFDemo/src/submit.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { ethers } from "ethers";
import { arrayify, hexlify, SigningKey, keccak256, recoverPublicKey, computeAddress, sha256 } from "ethers/lib/utils";
import { Buffer } from "buffer";
import secureRandom from "secure-random";

export async function setupSubmit(element: HTMLButtonElement) {

const randomnessContract = '0x67AdB577bAAcce02D436CaaEE005630f57A3C4e5'
const randomnessContract = '0xEAD4fC9fAEd0De8A68e82936238740E957Ccf865'

// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum);
Expand All @@ -17,6 +14,10 @@ export async function setupSubmit(element: HTMLButtonElement) {
element.addEventListener("click", async function(event: Event){
event.preventDefault()
const [myAddress] = await provider.send("eth_requestAccounts", []);
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xAA36A7' }], // chainId must be in hexadecimal numbers
});


// create the abi interface and encode the function data
Expand Down Expand Up @@ -55,11 +56,12 @@ export async function setupSubmit(element: HTMLButtonElement) {
console.log(`Request ID: ${originalRequestId}`);
// Additional data from the event can be accessed if needed
// You can also access other properties of the event object, like event.blockNumber

// Set up an event listener for the 'fulfilledRandomWords' event
randomnessContractInterface.on('fulfilledRandomWords', (requestId, randomWords, event) => {
// This code is executed when the event is emitted
if (originalRequestId == requestId) {
console.log(`Request ID: ${requestId}`);
console.log(`Callback with Request ID: ${requestId.toString()}`);
if (originalRequestId.toString() == requestId.toString()) {
console.log(`Random Words: ${randomWords}`);
// You can access other event properties like event.blockNumber if needed
document.querySelector<HTMLDivElement>('#preview')!.innerHTML = `
Expand All @@ -68,7 +70,7 @@ export async function setupSubmit(element: HTMLButtonElement) {
<h2>Transaction Parameters</h2>
<p><b>Request ID: ${requestId} </b></p>
<p><b>Random Words: ${randomWords} </b></p>
<p><b>Random Words: ${randomWords%6} </b></p>
<p style="font-size: 0.8em;">${JSON.stringify(tx_params)}</p>
`
}
Expand Down
11 changes: 10 additions & 1 deletion TNLS-Clients/payload-encryption/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,18 @@ document.querySelector<HTMLDivElement>('#app')!.innerHTML = `
</div>
</header>
<div>
<h2>Sample Application: Random Number Generation</h2>
<h2>Sample Application: Random Number Generation using Encrypted Payloads</h2>
<div id="form">
<button id="submit">Submit</button>
<form name="inputForm">
<br>
<label for="input1">Number of Random Words (up to 2000)</label>
<input type="number" placeholder="50" id="input1" name="input1" />
<br>
<br>
<label for="input2">Callback gas limit</label>
<input type="number" placeholder="300000" id="input2" name="input2" />
<br>
</div>
<div id="preview" style="word-wrap: break-word;">
Expand Down
103 changes: 42 additions & 61 deletions TNLS-Clients/payload-encryption/src/submit.ts

Large diffs are not rendered by default.

35 changes: 0 additions & 35 deletions TNLS-Gateways/public-gateway/script/DeployScript.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -20,31 +20,9 @@ contract DeployScript is Script {
TransparentUpgradeableProxy gatewayProxy;
RandomnessReciever randomnessAddress;

address verificationAddress = 0x8F2AE4b6aC67c8fFFac1Bf774956bC99F207B305;

string constant route = "pulsar-3";
//address verificationAddress = vm.envAddress("SECRET_GATEWAY_ETH_ADDRESS");

uint256 privKey = vm.envUint("ETH_PRIVATE_KEY");


/// @notice Get the encoded hash of the inputs for signing
/// @param _routeInput Route name
/// @param _verificationAddressInput Address corresponding to the route
function getRouteHash(string memory _routeInput, address _verificationAddressInput) public pure returns (bytes32) {
return keccak256(abi.encode(_routeInput, _verificationAddressInput));
}

/// @notice Hashes the encoded message hash
/// @param _messageHash the message hash
function getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) {
/*
Signature is produced by signing a keccak256 hash with the following format:
"\x19Ethereum Signed Message\n" + len(msg) + msg
*/
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash));
}

function run() public {
deployer = vm.rememberKey(privKey);
vm.startBroadcast();
Expand Down Expand Up @@ -77,19 +55,6 @@ contract DeployScript is Script {

randomnessAddress.setGatewayAddress(address(gateway));

// Initialize master verification Address
gateway.setMasterVerificationAddress(deployer); // Replace gatewayAddress with gateway
/// ------ Update Routes Param Setup ------- ///

// Update the route with with masterVerificationKey signature
bytes32 routeHash = getRouteHash(route, verificationAddress);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(routeHash);

(uint8 v, bytes32 r, bytes32 s) = vm.sign(privKey, ethSignedMessageHash);
bytes memory sig = abi.encodePacked(r, s, v);

gateway.updateRoute(route, verificationAddress, sig);

vm.stopBroadcast();
}
}
67 changes: 14 additions & 53 deletions TNLS-Gateways/public-gateway/src/Gateway.sol
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,19 @@ contract Gateway is Initializable {
Constants
//////////////////////////////////////////////////////////////*/

//Use hard coded constant values instead of storage variables for Secret VRF, saves around 8,500 in gas per TX.
//Use hard coded constant values instead of storage variables for Secret VRF, saves around 10,000+ in gas per TX.
//Since contract is upgradeable, we can update these values as well with it.
bytes constant routing_info = "secret1l4hr7wt4mm2fnvv5493ljlcngnfv2ewndk7tpc";
bytes constant routing_info = "secret1n8jh8qvjhu5ktce7v7ntlqac7u7wle6lvqnw38";
bytes constant routing_code_hash = "2a8c936d011446c0ae1f2503b4fb86455b7dc2c6899a56bd74edf9636f9517db";
string constant task_destination_network = "pulsar-3";
string constant task_destination_network = "secret-4";
address constant secret_gateway_signer_address = 0xeBbc93e856bA03e07f1D993B8D9b5fACc092eF3e;


/*//////////////////////////////////////////////////////////////
Structs
//////////////////////////////////////////////////////////////*/

struct ReducedTask {
struct Task {
bytes31 payload_hash_reduced;
bool completed;
}
Expand All @@ -54,7 +55,6 @@ contract Gateway is Initializable {

struct PostExecutionInfo {
bytes32 payload_hash;
bytes32 input_hash;
bytes32 packet_hash;
bytes20 callback_address;
bytes4 callback_selector;
Expand All @@ -68,14 +68,10 @@ contract Gateway is Initializable {
//////////////////////////////////////////////////////////////*/

address public owner;
address public masterVerificationAddress;
uint256 public taskId;

/// @dev Task ID ====> ReducedTask
mapping(uint256 => ReducedTask) public tasks;

/// @dev mapping of chain name string to the verification address
mapping(string => address) public route;
/// @dev Task ID ====> Task
mapping(uint256 => Task) public tasks;

/*//////////////////////////////////////////////////////////////
Errors
Expand All @@ -90,7 +86,6 @@ contract Gateway is Initializable {
/// @notice thrown when the signature is invalid
error InvalidSignature();


/// @notice thrown when the PacketSignature is invalid
error InvalidPacketSignature();

Expand Down Expand Up @@ -136,15 +131,6 @@ contract Gateway is Initializable {
return ecrecover(_signedMessageHash, v, r, s);
}

/// @notice Calculates the keccak256 hash of the route name and verification address
/// @param _routeInput The route name
/// @param _verificationAddressInput The verification address
/// @return The calculated hash

function getRouteHash(string calldata _routeInput, address _verificationAddressInput) private pure returns (bytes32) {
return keccak256(abi.encode(_routeInput, _verificationAddressInput));
}

/// @notice Slices the last byte of an bytes32 to make it into a bytes31
/// @param data The bytes32 data
/// @return The sliced bytes31 data
Expand All @@ -153,7 +139,6 @@ contract Gateway is Initializable {
return bytes31(data & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00);
}


/// @notice Encodes a bytes memory array into a Base64 string
/// @param data The bytes memory data to encode
/// @return The Base64 encoded string
Expand Down Expand Up @@ -276,31 +261,8 @@ contract Gateway is Initializable {
Maintainance Functions
//////////////////////////////////////////////////////////////*/

/// @notice Initialize the verification address
/// @param _masterVerificationAddress The input address

function setMasterVerificationAddress(address _masterVerificationAddress) external onlyOwner {
masterVerificationAddress = _masterVerificationAddress;
}

/// @notice Updating the route
/// @param _route Route name
/// @param _verificationAddress Address corresponding to the route
/// @param _signature Signed hashed inputs(_route + _verificationAddress)

function updateRoute(string calldata _route, address _verificationAddress, bytes calldata _signature) external onlyOwner {
bytes32 routeHash = getRouteHash(_route, _verificationAddress);
bytes32 ethSignedMessageHash = keccak256(bytes.concat("\x19Ethereum Signed Message:\n32", routeHash));

if (recoverSigner(ethSignedMessageHash, _signature) != masterVerificationAddress) {
revert InvalidSignature();
}

route[_route] = _verificationAddress;
}

/// @notice Increase the task_id to check for problems
/// @param _newTaskId Route name
/// @param _newTaskId the new task_id

function increaseTaskId(uint256 _newTaskId) external onlyOwner {
require (_newTaskId > taskId, "New task id must be higher than the old task_id");
Expand Down Expand Up @@ -335,7 +297,7 @@ contract Gateway is Initializable {
}

// persisting the task
tasks[taskId] = ReducedTask(sliceLastByte(_payloadHash), false);
tasks[taskId] = Task(sliceLastByte(_payloadHash), false);

//emit the task to be picked up by the relayer
emit logNewTask(
Expand Down Expand Up @@ -373,7 +335,7 @@ contract Gateway is Initializable {
bytes(uint256toString(_numWords)),
'}","routing_info": "',routing_info,
'","routing_code_hash": "',routing_code_hash,
'","user_address": "0x0000000000000000000000000000000000000000","user_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",', //unused user_address here + + 33 bytes of zeros in base64 for user_key
'","user_address": "0x0000000000000000000000000000000000000000","user_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",', //unused user_address here + 33 bytes of zeros in base64 for user_key
'"callback_address": "', bytes(callback_address),
'","callback_selector": "OLpGFA==",', // 0x38ba4614 hex value already converted into base64, callback_selector of the fullfillRandomWords function
'"callback_gas_limit": ', bytes(uint256toString(_callbackGasLimit)),'}'
Expand All @@ -395,7 +357,7 @@ contract Gateway is Initializable {
});

// persisting the task
tasks[taskId] = ReducedTask(sliceLastByte(payloadHash), false);
tasks[taskId] = Task(sliceLastByte(payloadHash), false);

//emit the task to be picked up by the relayer
emit logNewTask(
Expand Down Expand Up @@ -424,7 +386,7 @@ contract Gateway is Initializable {

function postExecution(uint256 _taskId, string calldata _sourceNetwork, PostExecutionInfo calldata _info) external {

ReducedTask storage task = tasks[_taskId];
Task storage task = tasks[_taskId];

// Check if the task is already completed
if (task.completed) {
Expand All @@ -441,18 +403,17 @@ contract Gateway is Initializable {
bytes(_sourceNetwork),
bytes(uint256toString(block.chainid)),
bytes32(_taskId),
_info.input_hash,
_info.payload_hash,
_info.result,
_info.callback_address,
_info.callback_selector);

// Perform Keccak256 + sha256 hash
bytes32 packetHash = sha256(abi.encodePacked(keccak256(data)));
bytes32 packetHash = sha256(bytes.concat(keccak256(data)));

// Packet signature verification
if ((_info.packet_hash != packetHash) ||
recoverSigner(_info.packet_hash, _info.packet_signature) != route[_sourceNetwork]) {
recoverSigner(_info.packet_hash, _info.packet_signature) != secret_gateway_signer_address) {
revert InvalidPacketSignature();
}

Expand Down
Loading

0 comments on commit 62a69cf

Please sign in to comment.