Skip to content

Commit

Permalink
More info saved in TaskInfo, change Task_id u64 to string
Browse files Browse the repository at this point in the history
  • Loading branch information
SecretSaturn committed Jan 26, 2024
1 parent 5e73c24 commit e109f75
Show file tree
Hide file tree
Showing 11 changed files with 106 additions and 51 deletions.
12 changes: 0 additions & 12 deletions TNLS-Clients/node_modules/.yarn-integrity

This file was deleted.

50 changes: 50 additions & 0 deletions TNLS-Gateways/public-gateway/script/DeployScript.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.23;

import "forge-std/Test.sol";
import "forge-std/Vm.sol";
import "forge-std/console2.sol";
import "forge-std/Script.sol";
import {Gateway} from "../src/Gateway.sol";
import {RandomnessReciever} from "../src/RandomnessReciever.sol";
import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";


contract DeployScript is Script {
function setUp() public {}

ProxyAdmin proxyAdmin;
Gateway gatewayLogic;
TransparentUpgradeableProxy gatewayProxy;
RandomnessReciever randomnessAddress;

function run() public {
vm.startBroadcast();

// Deploy Gateway Logic Contract
gatewayLogic = new Gateway();

// Prepare initializer data for Gateway
bytes memory initializerData = abi.encodeWithSelector(
Gateway.initialize.selector
);

// Deploy TransparentUpgradeableProxy
gatewayProxy = new TransparentUpgradeableProxy(
address(gatewayLogic),
address(msg.sender),
initializerData
);

// Cast the proxy address to the Gateway interface
Gateway gateway = Gateway(address(gatewayProxy));

randomnessAddress = new RandomnessReciever();
console2.logAddress(address(gateway));

randomnessAddress.setGatewayAddress(address(gateway));

vm.stopBroadcast();
}
}
4 changes: 2 additions & 2 deletions TNLS-Gateways/public-gateway/script/UpgradeScript.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ contract UpgradeScript is Script {
// Deploy New Gateway Logic Contract
newGatewayLogic = new Gateway();

gatewayProxyAdmin = ProxyAdmin(0x5B7191206b913F892956d7880C041dc1A764016C);
gatewayProxyAdmin = ProxyAdmin(0xdDC6d94d9f9FBb0524f069882d7C98241040472E);

bytes memory selector = abi.encodeWithSelector(Gateway.upgradeHandler.selector);
gatewayProxyAdmin.upgradeAndCall(ITransparentUpgradeableProxy(0x5e1e92eA6A1b7a58D88619C625FEc5D27147bc64), address(newGatewayLogic),selector);
gatewayProxyAdmin.upgradeAndCall(ITransparentUpgradeableProxy(0xfaFCfceC4e29e9b4ECc8C0a3f7df1011580EEEf2), address(newGatewayLogic),selector);

vm.stopBroadcast();
}
Expand Down
22 changes: 11 additions & 11 deletions TNLS-Gateways/public-gateway/src/Gateway.sol
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ contract Gateway is Initializable, OwnableUpgradeable {
//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 = "secret1udj6x7393y73xr5pevu4u30tuy9j650ljfm25d";
bytes constant routing_info = "secret1sajypa5fkkh2yzjuadv4fp97dl5w7pzd0wtrhx";
bytes constant routing_code_hash = "ba0006753cb18a8b12fe266707289098bfb8a3ae83de54ecece591231ada2abf";
string constant task_destination_network = "pulsar-3";
address constant secret_gateway_signer_address = 0x9BEb147dADd9c246B5443Ca89fB56a612236aeEb;
address constant secret_gateway_signer_address = 0x8CEEC0f0960571A6ad8B23970EEE30246aABCA8F;

/*//////////////////////////////////////////////////////////////
Structs
Expand Down Expand Up @@ -418,20 +418,20 @@ contract Gateway is Initializable, OwnableUpgradeable {

// Concatenate packet data elements
bytes memory data = bytes.concat(
bytes(_sourceNetwork),
bytes(uint256toString(block.chainid)),
bytes32(_taskId),
_info.payload_hash,
_info.result,
_info.callback_address,
_info.callback_selector);
bytes(_sourceNetwork),
bytes(uint256toString(block.chainid)),
bytes32(_taskId),
_info.payload_hash,
_info.result,
_info.callback_address,
_info.callback_selector
);

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

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

Expand Down
Binary file modified TNLS-Gateways/secret/contract.wasm.gz
Binary file not shown.
21 changes: 12 additions & 9 deletions TNLS-Gateways/secret/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ pub fn instantiate(
let state = State {
admin: admin_raw,
keyed: false,
tx_cnt: 0,
encryption_keys: KeyPair::default(),
signing_keys: KeyPair::default(),
};
Expand Down Expand Up @@ -205,7 +204,7 @@ fn pre_execution(deps: DepsMut, _env: Env, msg: PreExecutionMsg) -> StdResult<Re
Err(_) => {
unsafe_payload = true;
// If decryption fails, continue with the original, encrypted payload
// Note: We are not verifying the payload in this case as it's already deemed unsafe
// We are not verifying the payload in this case as it's already deemed unsafe
from_binary(&Binary::from(msg.payload.as_slice()))?
},
};
Expand Down Expand Up @@ -252,16 +251,24 @@ fn pre_execution(deps: DepsMut, _env: Env, msg: PreExecutionMsg) -> StdResult<Re

// combine input values and task to create verification hash
let unsafe_payload_bytes = if unsafe_payload { [1u8] } else { [0u8] };
let input_hash = sha_256(&[input_values.as_bytes(), &new_task.task_id.to_be_bytes(),&unsafe_payload_bytes].concat());
let input_hash = sha_256(&[input_values.as_bytes(), new_task.task_id.as_bytes(),&unsafe_payload_bytes].concat());

// create a task information store
let task_info = TaskInfo {
payload: msg.payload, // storing the payload
payload_hash: msg.payload_hash,
payload_signature: msg.payload_signature,
decrypted_payload_data: input_values.clone(),
routing_info: msg.routing_info.clone(),
routing_code_hash: msg.routing_code_hash.clone(),
user_pubkey: msg.user_pubkey,
handle: msg.handle.clone(),
nonce: msg.nonce,
unsafe_payload: unsafe_payload, //store the unsafe_payload flag for later checks
input_hash, // storing the input_values hashed together with task
source_network: msg.source_network,
user_address: payload.user_address.clone(),
user_key: payload.user_key.clone(),
callback_address: payload.callback_address.clone(),
callback_selector: payload.callback_selector,
callback_gas_limit: payload.callback_gas_limit
Expand Down Expand Up @@ -335,15 +342,11 @@ fn post_execution(deps: DepsMut, env: Env, msg: PostExecutionMsg) -> StdResult<R
// "hasher" is used to perform multiple Keccak256 hashes
let mut hasher = Keccak256::new();

let mut task_id_padded = [0u8; 32]; // Create a 32-byte array filled with zeros
// Convert the task_id to an 8-byte big-endian array & Copy the 8-byte big-endian representation to the end of the result array
task_id_padded[32 - msg.task.task_id.to_be_bytes().len()..].copy_from_slice(msg.task.task_id.to_be_bytes().as_slice());

// create hash of entire packet (used to verify the message wasn't modified in transit)
let data = [
env.block.chain_id.as_bytes(), // source network
routing_info.as_bytes(), // task_destination_network
task_id_padded.as_slice(), // task ID
msg.task.task_id.as_bytes(), // task ID
task_info.payload_hash.as_slice(), // original payload message
result.as_slice(), // result
task_info.callback_address.as_slice(), // callback address
Expand Down Expand Up @@ -422,7 +425,7 @@ fn post_execution(deps: DepsMut, env: Env, msg: PostExecutionMsg) -> StdResult<R
let result_info = ResultInfo {
source_network: env.block.chain_id,
task_destination_network: routing_info,
task_id: msg.task.task_id.to_string(),
task_id: msg.task.task_id.clone(),
payload_hash: payload_hash,
result: result,
packet_hash: packet_hash,
Expand Down
4 changes: 2 additions & 2 deletions TNLS-Gateways/secret/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub struct PublicKeyResponse {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct PreExecutionMsg {
/// Task ID generated by the public gateway.
pub task_id: u64,
pub task_id: String,
/// Source network (where to go once pulled into the next gateway).
pub source_network: String,
/// Destination contract address.
Expand Down Expand Up @@ -168,7 +168,7 @@ pub struct BroadcastMsg {
/// Encryption of (data, routing info, and user info).
pub payload: Binary,
/// Task ID coming from the gateway.
pub task_id: u64,
pub task_id: String,
/// SHA256 hash of (result, packet, task_id).
pub output_hash: Binary,
/// `output_hash` signed with Private Gateway key.
Expand Down
28 changes: 21 additions & 7 deletions TNLS-Gateways/secret/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ pub static CONFIG: Item<State> = Item::new(b"config");
pub static MY_ADDRESS: Item<CanonicalAddr> = Item::new(b"myaddr");
/// Storage key for the contract instantiator.
pub static CREATOR: Item<CanonicalAddr> = Item::new(b"creator");
/// Storage key for task IDs.
/// Storage key for tasks.
pub static TASK_MAP: Keymap<Task, TaskInfo> = Keymap::new(b"tasks");
/// Storage key for task IDs.
/// Storage key for results.
pub static RESULT_MAP: Keymap<Task, ResultInfo> = Keymap::new(b"results");

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
Expand All @@ -21,8 +21,6 @@ pub struct State {
pub admin: CanonicalAddr,
/// Status of gateway key generation.
pub keyed: bool,
/// Count of tx.
pub tx_cnt: u64,
/// Private gateway encryption key pair.
pub encryption_keys: KeyPair,
/// Private gateway signing key pair.
Expand All @@ -33,8 +31,8 @@ pub struct State {
pub struct Task {
/// The network of the Task
pub network: String,
/// The task id of the test
pub task_id: u64,
/// The task id of the Task
pub task_id: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
Expand All @@ -43,7 +41,23 @@ pub struct TaskInfo {
pub payload: Binary,
/// The original payload_hash from the front-end.
pub payload_hash: Binary,
/// The original payload_hash from the front-end.
/// Signature of hash of encrypted input values.
pub payload_signature: Binary,
/// The decrypted payload.
pub decrypted_payload_data: String,
/// User public chain address.
pub routing_info: Addr,
/// Destination contract code hash.
pub routing_code_hash: String,
/// Encryption of (data, routing info, and user info).
pub user_key: Binary,
/// User's wallet public key.
pub user_pubkey: Binary,
/// Handle to be called at destination contract.
pub handle: String,
/// Unique random bytes used to encrypt payload.
pub nonce: Binary,
//Flag if payload is deemed unsafe.
pub unsafe_payload: bool,
/// A unique hash for the task.
pub input_hash: [u8; 32],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ fn try_add_one<S: Storage, A: Api, Q: Querier>(
deps: &mut Extern<S, A, Q>,
_env: Env,
input_values: String,
task_id: u64,
task_id: String,
input_hash: Binary,
) -> HandleResult {
// increment count each time this handle is called
Expand Down
6 changes: 3 additions & 3 deletions TNLS-Relayers/base_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class Task:

def __init__(self, task_dict):
task_dict = dict(task_dict)
if 'task_id' in task_dict:
if 'task_id' in task_dict:
task_dict['task_id'] = str(task_dict['task_id'])
if 'task_destination_network' in task_dict:
self.task_destination_network = task_dict['task_destination_network']
Expand All @@ -119,8 +119,8 @@ def __str__(self):
return json.dumps(new_task_list)
return json.dumps(to_dict(new_task_dict, key_type=self.task_destination_network))
else:
if 'task_id' in self.task_data and self.task_destination_network in scrt_chains:
self.task_data['task_id'] = int(self.task_data['task_id'])
#if 'task_id' in self.task_data and self.task_destination_network in scrt_chains:
# self.task_data['task_id'] = int(self.task_data['task_id'])
return json.dumps(to_dict(self.task_data))

def __repr__(self):
Expand Down
Loading

0 comments on commit e109f75

Please sign in to comment.