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

remove getStorageAt returning token and use local storage instead #2200

Merged
merged 4 commits into from
Dec 17, 2024
Merged
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
1 change: 0 additions & 1 deletion go/common/custom_query_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import "github.com/ethereum/go-ethereum/common"

// CustomQuery methods
const (
UserIDRequestCQMethod = "0x0000000000000000000000000000000000000001"
ListPrivateTransactionsCQMethod = "0x0000000000000000000000000000000000000002"
CreateSessionKeyCQMethod = "0x0000000000000000000000000000000000000003"
ActivateSessionKeyCQMethod = "0x0000000000000000000000000000000000000004"
Expand Down
49 changes: 0 additions & 49 deletions integration/tengateway/tengateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ func TestTenGateway(t *testing.T) {
"testSubscriptionTopics": testSubscriptionTopics,
"testDifferentMessagesOnRegister": testDifferentMessagesOnRegister,
"testInvokeNonSensitiveMethod": testInvokeNonSensitiveMethod,
"testGetStorageAtForReturningUserID": testGetStorageAtForReturningUserID,
// "testRateLimiter": testRateLimiter,
"testSessionKeys": testSessionKeys,
} {
Expand Down Expand Up @@ -899,54 +898,6 @@ func testInvokeNonSensitiveMethod(t *testing.T, _ int, httpURL, wsURL string, w
}
}

func testGetStorageAtForReturningUserID(t *testing.T, _ int, httpURL, wsURL string, w wallet.Wallet) {
user, err := NewGatewayUser([]wallet.Wallet{w}, httpURL, wsURL)
require.NoError(t, err)

type JSONResponse struct {
Result string `json:"result"`
}
var response JSONResponse

// make a request to GetStorageAt with correct parameters to get userID that exists in the database
respBody := makeHTTPEthJSONReq(httpURL, "eth_getStorageAt", user.tgClient.UserID(), []interface{}{common.UserIDRequestCQMethod, "0", nil})
if err = json.Unmarshal(respBody, &response); err != nil {
t.Error("Unable to unmarshal response")
}
if !bytes.Equal(gethcommon.FromHex(response.Result), user.tgClient.UserIDBytes()) {
t.Errorf("Wrong ID returned. Expected: %s, received: %s", user.tgClient.UserID(), response.Result)
}

// make a request to GetStorageAt with correct parameters to get userID, but with wrong userID
respBody2 := makeHTTPEthJSONReq(httpURL, "eth_getStorageAt", "0x0000000000000000000000000000000000000001", []interface{}{common.UserIDRequestCQMethod, "0", nil})
if !strings.Contains(string(respBody2), "not found") {
t.Error("eth_getStorageAt did not respond with not found error")
}

err = user.RegisterAccounts()
if err != nil {
t.Errorf("Failed to register accounts: %s", err)
return
}

// make a request to GetStorageAt with wrong parameters to get userID, but correct userID
respBody3 := makeHTTPEthJSONReq(httpURL, "eth_getStorageAt", user.tgClient.UserID(), []interface{}{"0x0000000000000000000000000000000000000007", "0", nil})
expectedErr := "not supported"
if !strings.Contains(string(respBody3), expectedErr) {
t.Errorf("eth_getStorageAt did not respond with error: %s, it was: %s", expectedErr, string(respBody3))
}

privateTxs, _ := json.Marshal(common.ListPrivateTransactionsQueryParams{
Address: gethcommon.HexToAddress("0xA58C60cc047592DE97BF1E8d2f225Fc5D959De77"),
Pagination: common.QueryPagination{Size: 10},
})

respBody4 := makeHTTPEthJSONReq(httpURL, "eth_getStorageAt", user.tgClient.UserID(), []interface{}{common.ListPrivateTransactionsCQMethod, string(privateTxs), nil})
if err = json.Unmarshal(respBody4, &response); err != nil {
t.Error("Unable to unmarshal response")
}
}

func makeRequestHTTP(url string, body []byte) []byte {
generateViewingKeyBody := bytes.NewBuffer(body)
resp, err := http.Post(url, "application/json", generateViewingKeyBody) //nolint:noctx,gosec
Expand Down
1 change: 0 additions & 1 deletion packages/ui/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ export const requestMethods = {
requestAccounts: "eth_requestAccounts",
switchNetwork: "wallet_switchEthereumChain",
addNetwork: "wallet_addEthereumChain",
getStorageAt: "eth_getStorageAt",
signTypedData: "eth_signTypedData_v4",
getChainId: "eth_chainId",
};
23 changes: 8 additions & 15 deletions tools/walletextension/frontend/src/api/ethRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,27 +82,20 @@ export const getSignature = async (account: string, data: any) => {
}
};

export const getToken = async (provider: ethers.providers.Web3Provider) => {
if (!provider.send) {
return null;
}
export const getToken = async () => {
try {
if (await isTenChain()) {
const token = await provider.send(requestMethods.getStorageAt, [
userStorageAddress,
getRandomIntAsString(0, 1000),
null,
]);
return token;
} else {
return null;
}
const token = localStorage.getItem('ten_token') || '';
return token;
} catch (e: any) {
console.error(e);
throw e;
}
};

export const clearToken = () => {
localStorage.removeItem('ten_token');
};

export async function addNetworkToMetaMask(rpcUrls: string[]) {
if (!ethereum) {
throw "No ethereum object found";
Expand Down Expand Up @@ -150,7 +143,7 @@ export async function authenticateAccountWithTenGatewayEIP712(
...typedData,
message: {
...typedData.message,
"Encryption Token": token,
"Encryption Token": token,
},
};
const signature = await getSignature(account, data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { ToastType } from "@/types/interfaces";
import {
authenticateAccountWithTenGatewayEIP712,
getToken,
clearToken
} from "@/api/ethRequests";
import { ethers } from "ethers";
import ethService from "@/services/ethService";
Expand Down Expand Up @@ -56,7 +57,7 @@ export const WalletConnectionProvider = ({
try {
await ethService.checkIfMetamaskIsLoaded(providerInstance);

const fetchedToken = await getToken(providerInstance);
const fetchedToken = await getToken();
setToken(fetchedToken);

const status = await ethService.isUserConnectedToTenChain(fetchedToken);
Expand Down Expand Up @@ -124,6 +125,7 @@ export const WalletConnectionProvider = ({
setAccounts(null);
setWalletConnected(false);
setToken("");
clearToken();
}
};

Expand All @@ -135,7 +137,7 @@ export const WalletConnectionProvider = ({
);
return;
}
const token = await getToken(provider);
const token = await getToken();

if (!isValidTokenFormat(token)) {
showToast(
Expand Down Expand Up @@ -194,6 +196,7 @@ export const WalletConnectionProvider = ({
setAccounts(null);
setWalletConnected(false);
setToken("");
clearToken();
} else {
window.location.reload();
}
Expand Down
2 changes: 1 addition & 1 deletion tools/walletextension/frontend/src/services/ethService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ const ethService = {
return;
}

const token = await getToken(provider);
const token = await getToken();

if (!token || !isValidTokenFormat(token)) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,14 @@ const useGatewayService = () => {
// SWITCHED_CODE=4902; error 4902 means that the chain does not exist
if (
switched === SWITCHED_CODE ||
!isValidTokenFormat(await getToken(provider))
!isValidTokenFormat(await getToken())
) {
showToast(ToastType.INFO, "Adding TEN Testnet...");
const user = await joinTestnet();

// Store the token in localStorage
localStorage.setItem("ten_token", "0x" + user);

const rpcUrls = [
`${tenGatewayAddress}/${tenGatewayVersion}/?token=${user}`,
];
Expand Down
2 changes: 0 additions & 2 deletions tools/walletextension/rpcapi/blockchain_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,6 @@ func (api *BlockChainAPI) GetStorageAt(ctx context.Context, address gethcommon.A
}

switch address.Hex() {
case common.UserIDRequestCQMethod: // todo - review whether we need this endpoint
return user.ID, nil
case common.ListPrivateTransactionsCQMethod:
// sensitive CustomQuery methods use the convention of having "address" at the top level of the params json
userAddr, err := extractCustomQueryAddress(params)
Expand Down
Loading
Loading