diff --git a/design/ux/Obscuro_Gateway.md b/design/ux/Ten_Gateway.md similarity index 66% rename from design/ux/Obscuro_Gateway.md rename to design/ux/Ten_Gateway.md index 6dad2356f3..9c7acf43bb 100644 --- a/design/ux/Obscuro_Gateway.md +++ b/design/ux/Ten_Gateway.md @@ -1,16 +1,16 @@ # The Ten Gateway - Design -The scope of this document is to design a hosted [Wallet Extension](wallet_extension.md) called the "Ten Gateway" (OG). +The scope of this document is to design a hosted [Wallet Extension](wallet_extension.md) called the "Ten Gateway" (TG). -The OG will be a superset of the WE functionality, so this document will only cover the additions. +The TG will be a superset of the WE functionality, so this document will only cover the additions. ## High level overview -The OG will be a [Confidential Web Service](https://medium.com/p/983a2a67fc08), running inside SGX. +The TG will be a [Confidential Web Service](https://medium.com/p/983a2a67fc08), running inside SGX. The current WE is designed to be used by a single user holding multiple addresses accross potentially multiple wallets. -The OG must support mutiple users, each with multiple addresses. It can be seen as offering a WE per user. +The TG must support mutiple users, each with multiple addresses. It can be seen as offering a WE per user. The Ten node has no concept of "User". It only authenticates based on the "blockchain address". It expects to be supplied with a signed viewing key per address, so that it can respond encrypted with that VK. @@ -22,7 +22,7 @@ The AVKs are stored on the local computer in a file. An AVK is a text containing the hash of the public viewing key signed with the "spending key" that controls a blockchain address. -The diagram below depicts the setup once the OG is implemented. +The diagram below depicts the setup once the TG is implemented. ![Architecture diagram](resources/og_arch.png) ```plantuml @startuml @@ -47,9 +47,9 @@ component "Bob's Computer"{ } component "Confidential Web Service"{ node "Ten Gateway" - database "OG Viewing Keys" + database "TG Viewing Keys" } -"OG Viewing Keys" <-> "Ten Gateway" +"TG Viewing Keys" <-> "Ten Gateway" Bob --> "Bob's MetaMask" "Bob's MetaMask" ---> "Ten Gateway" : HTTPS @@ -66,11 +66,11 @@ Charlie --> "Charlie's MetaMask" @enduml ``` -Notice that the OG is a multi-tenant WE running inside SGX and storing the authenticated viewing keys (and other information) in an encrypted database. +Notice that the TG is a multi-tenant WE running inside SGX and storing the authenticated viewing keys (and other information) in an encrypted database. ## User interactions -The key reason for the OG is to allow implementing a 3-click user onboarding process. +The key reason for the TG is to allow implementing a 3-click user onboarding process. ### User on-boarding @@ -86,25 +86,25 @@ autonumber actor "Alice's Browser" as Alice participant MetaMask as MM -participant "https://gateway.ten.org/v1" as OG +participant "https://gateway.ten.org/v1" as TG participant "https://ten.org" as ON group First click Alice -> ON: Join Ten - ON --> Alice: Redirect to OG + ON --> Alice: Redirect to TG note right The point of this sequence is to call the "Create User" - endpoint on the OG + endpoint on the TG end note - Alice -> OG: Create User\n(ajax call behind the scenes) - OG -> OG: Generate and record VK\nand record against UserId + Alice -> TG: Create User\n(ajax call behind the scenes) + TG -> TG: Generate and record VK\nand record against UserId note right The UserId is the hash of the Public Key of the VK end note - OG -> Alice: Send UserId - Alice -> MM: Automatically add "Ten" network with RPC\n"https://gateway.ten.org/v1?u=$UserId" + TG -> Alice: Send Encryption token + Alice -> MM: Automatically add "Ten" network with RPC\n"https://gateway.ten.org/v1?token=$EncryptionToken" end group Second click @@ -121,7 +121,7 @@ group Third click Alice -> MM : Confirm signature end -Alice -> OG: All further Ten interactions will be to\nhttps://gateway.ten.org/v1?u=$UserId +Alice -> TG: All further Ten interactions will be to\nhttps://gateway.ten.org/v1?token=$EncryptionToken @enduml ``` @@ -151,36 +151,36 @@ types: { chainId: obscuroChainIDDecimal, }, message: { - "Encryption Token": "0x"+userID + "Encryption Token": "0x"+encryptionToken }, }; ``` ##### Click 1 -1. Behind the scenes, a js functions calls "gateway.ten.org/v1/join" where it will generate a VK and send back the hash of the Public key. This is the "UserId" -2. After receiving the UserId, the js function will add a new network to the wallet. -The RPC URL of the new Ten network will include the userid: "https://gateway.ten.org/v1?u=$UserId". -Notice that the UserId has to be included as a query parameter because it must be encrypted by https, as it is secret. +1. Behind the scenes, a js functions calls "gateway.ten.org/v1/join" where it will generate a VK and send back the hash of the Public key. This is the "encryption token" +2. After receiving the Encryption token, the js function will add a new network to the wallet. +The RPC URL of the new Ten network will include the encryption token: "https://gateway.ten.org/v1?token=$EncryptionToken". +Notice that the encryption token has to be included as a query parameter because it must be encrypted by https, as it is secret. ##### Click 2 After these actions are complete, the same page will now ask the user to connect the wallet and switch to Ten. Automatically, the page will open metamask and ask the user to sign over an EIP-712 formatted message as described above. ##### Click 3 -Once signed, this will be submitted in the background to: "https://gateway.ten.org/v1?u=$UserId&action=register" +Once signed, this will be submitted in the background to: "https://gateway.ten.org/v1?token=$EncryptionToken&action=register" -Note: Any further accounts will be registered similarly for the same UserId. +Note: Any further accounts will be registered similarly for the same encryption token. -Note: The user must guard the UserId. Anyone who can read it, will be able to read the data of this user. +Note: The user must guard the encryption token. Anyone who can read it, will be able to read the data of this user. Note: Alternative UXes that achieve the same goal are ok. ### Register subsequent addresses -User Alice is onboarded already and has the Ten network configured in her wallet with a UserId. +User Alice is onboarded already and has the Ten network configured in her wallet with an encryption token. She has to go to the same landing page as above and connect her wallet, instead of hitting "Join". When connecting, she can choose a second account. @@ -192,51 +192,52 @@ After signing it will submit to the server The curent WE is single-tenant. It assumes that all registered blockchain addresses belong to the same user. -The OG will keep a many-to-one relationship between addresses and users. It will have multiple users, each with multiple addresses. +The TG will keep a many-to-one relationship between addresses and users. It will have multiple users, each with multiple addresses. -Each request to the OG (except "/join") must have the "u" query parameter. -The first thing, the WE will lookup the userId and then operate in "Wallet Extension" mode, after loading all addresses. +Each request to the TG (except "/join") must have the "u" query parameter. +The first thing, the WE will lookup the encryption token and then operate in "Wallet Extension" mode, after loading all addresses. -Note that the system considers the realm of a UserId as completely independent. Multiple users could register the same addrss, -if they somehow control the spending key. It shouldn't matter since they have different userIds +Note that the system considers the realm of an encryption token as completely independent. Multiple users could register the same addrss, +if they somehow control the spending key. +It shouldn't matter since they have different encryption tokens ## HTTP Endpoints ### Create User - GET "/join" - Generates a key-pair. -- Hashes the public key of the VK - this is the UserId. -- Stores in the db: UserId, PrivateKey -- Return UserId +- Hashes the public key of the VK - this is the encryption token. +- Stores in the db: EncryptionToken, PrivateKey +- Return encryption token Note: Has to be protected against DDOS attacks. -### Query address - Get "/query/address?u=$UserId&a=$Address" +### Query address - Get "/query/address?token=$EncryptionToken&a=$Address" This endpoints responds a json of true or false if the address "a" is already registered for user "u" -### Authenticate address - POST "/authenticate?u=$UserId" +### Authenticate address - POST "/authenticate?token=$EncryptionToken" JSON Fields: - address - signature -This call will be made by a javascript function after it has collected the signed text containing the UserId and the Address from the wallet. +This call will be made by a javascript function after it has collected the signed text containing the encryption token and the Address from the wallet. -This call is equivalent to the current: "submitviewingkey/", but instead it will save the information against the UserId. +This call is equivalent to the current: "submitviewingkey/", but instead it will save the information against the encryption token. Actions: -- check the text is well formed and extract the userId and address -- check the UserId corresponds to the one in the text +- check the text is well formed and extract the encryption token and address +- check the encryption token corresponds to the one in the text - check the signature corresponds to the address and is valid -- save the text+signature against the userId +- save the text+signature against the encryption token -### Revoke UserId - POST "/revoke?u=$UserId" +### Revoke Encryption token - POST "/revoke?t=$EncryptionToken" -When this endpoint is triggered, the userId with the authenticated viewing keys should be deleted. +When this endpoint is triggered, the encryption token with the authenticated viewing keys should be deleted. ### ETH RPC endpoints All the Eth RPC endpoints are implemented as they are now in the WE. -The difference is that the UserId must be checked before any logic, and the registered addresses for that user are loaded in context. +The difference is that the encryption token must be checked before any logic, and the registered addresses for that user are loaded in context. ## SGX @@ -253,7 +254,7 @@ Note that the current WE implements most of this flow. ## Upgradability -When the OG is upgraded, the database with viewing keys has to be handed over to the new version. +When the TG is upgraded, the database with viewing keys has to be handed over to the new version. The best mechanism is to use the transparent upgrading approval we have for the enclave based on an event from the Management Contract. @@ -268,17 +269,17 @@ I propose to start gradually by adding functionality that doesn't break the WE. The tests can use sqlite, same as we do for the enclave. And in the real setup it will be edgelessdb. This code can be extracted from the enclave and made reusable. -2. Store the VKs in the database against a hardcoded userId and create the logic to fetch them based on the hardcoded userId. +2. Store the VKs in the database against a hardcoded encryption token and create the logic to fetch them based on the hardcoded encryption token. Note: At this stage there is no functional change of the wallet extension. Just prepararation. -3. Add the UserId parameter in all request handlers. +3. Add the encryption token parameter in all request handlers. -Note: still no functional change, except that now all the rpc urls in the test need "?u=1" to work +Note: still no functional change, except that now all the rpc urls in the test need "?token1" to work 4. Change the format of the signed string and implement the authenticate endpoint. -5. Do the rest of the wiring of the userId +5. Do the rest of the wiring of the encryption token 6. Implement the "join" endpoint, and make sure everything works E2E @@ -295,7 +296,7 @@ Very simple interface to show that the 3-click approach is possible. # Advanced features -## Allowing users to create accounts on the OG +## Allowing users to create accounts on the TG Maybe using single-sign On. This will allow advanced features. @@ -304,14 +305,14 @@ This will allow advanced features. This could be used for tax purposes, or to prove holdings. -## Revocation of userId +## Revocation of encryption token Users might suspect someone else knows their UserdId. -Note: forgotten userIds are not a problem, because they have high enough entropy. +Note: forgotten encryption tokens are not a problem, because they have high enough entropy. There must be a UI which calls the revocation endpoint. -Note that if the OG operator comes into possession of a UserId, they can circumvent the revocation by launching the service +Note that if the TG operator comes into possession of an encryption token, they can circumvent the revocation by launching the service against a snapshot of the database. To prevent this, revocations could be published on ledger, and make them a first class citizen. diff --git a/integration/constants.go b/integration/constants.go index 1e9f85ed83..37dee9b2f0 100644 --- a/integration/constants.go +++ b/integration/constants.go @@ -12,24 +12,24 @@ const ( StartPortWalletExtensionUnitTest = 40000 StartPortFaucetUnitTest = 41000 StartPortFaucetHTTPUnitTest = 42000 - StartPortObscuroscanUnitTest = 43000 - StartPortObscuroGatewayUnitTest = 44000 + StartPortTenscanUnitTest = 43000 + StartPortTenGatewayUnitTest = 44000 - DefaultGethWSPortOffset = 100 - DefaultGethAUTHPortOffset = 200 - DefaultGethNetworkPortOffset = 300 - DefaultPrysmHTTPPortOffset = 400 - DefaultPrysmP2PPortOffset = 500 - DefaultHostP2pOffset = 600 // The default offset for the host P2p - DefaultEnclaveOffset = 700 // The default offset between a Geth nodes port and the enclave ports. Used in Socket Simulations. - DefaultHostRPCHTTPOffset = 800 // The default offset for the host's RPC HTTP port - DefaultHostRPCWSOffset = 900 // The default offset for the host's RPC websocket port - DefaultObscuroscanHTTPPortOffset = 910 - DefaultObscuroGatewayHTTPPortOffset = 930 - DefaultObscuroGatewayWSPortOffset = 940 + DefaultGethWSPortOffset = 100 + DefaultGethAUTHPortOffset = 200 + DefaultGethNetworkPortOffset = 300 + DefaultPrysmHTTPPortOffset = 400 + DefaultPrysmP2PPortOffset = 500 + DefaultHostP2pOffset = 600 // The default offset for the host P2p + DefaultEnclaveOffset = 700 // The default offset between a Geth nodes port and the enclave ports. Used in Socket Simulations. + DefaultHostRPCHTTPOffset = 800 // The default offset for the host's RPC HTTP port + DefaultHostRPCWSOffset = 900 // The default offset for the host's RPC websocket port + DefaultTenscanHTTPPortOffset = 910 + DefaultTenGatewayHTTPPortOffset = 930 + DefaultTenGatewayWSPortOffset = 940 ) const ( EthereumChainID = 1337 - ObscuroChainID = 443 + TenChainID = 443 ) diff --git a/integration/contractdeployer/contract_deployer_test.go b/integration/contractdeployer/contract_deployer_test.go index 423028caa1..93785918e7 100644 --- a/integration/contractdeployer/contract_deployer_test.go +++ b/integration/contractdeployer/contract_deployer_test.go @@ -56,7 +56,7 @@ func TestCanDeployLayer2ERC20Contract(t *testing.T) { NodePort: uint(hostWSPort), IsL1Deployment: false, PrivateKey: contractDeployerPrivateKeyHex, - ChainID: big.NewInt(integration.ObscuroChainID), + ChainID: big.NewInt(integration.TenChainID), ContractName: contractdeployer.Layer2Erc20Contract, ConstructorParams: []string{erc20ParamOne, erc20ParamTwo, erc20ParamThree}, } @@ -66,7 +66,7 @@ func TestCanDeployLayer2ERC20Contract(t *testing.T) { panic(err) } - contractDeployerWallet := wallet.NewInMemoryWalletFromConfig(contractDeployerPrivateKeyHex, integration.ObscuroChainID, testlog.Logger()) + contractDeployerWallet := wallet.NewInMemoryWalletFromConfig(contractDeployerPrivateKeyHex, integration.TenChainID, testlog.Logger()) contractDeployerClient := getClient(hostWSPort, contractDeployerWallet) var deployedCode string @@ -85,10 +85,10 @@ func TestFaucetSendsFundsOnlyIfNeeded(t *testing.T) { hostWSPort := startPort + integration.DefaultHostRPCWSOffset createObscuroNetwork(t, startPort) - faucetWallet := wallet.NewInMemoryWalletFromConfig(genesis.TestnetPrefundedPK, integration.ObscuroChainID, testlog.Logger()) + faucetWallet := wallet.NewInMemoryWalletFromConfig(genesis.TestnetPrefundedPK, integration.TenChainID, testlog.Logger()) faucetClient := getClient(hostWSPort, faucetWallet) - contractDeployerWallet := wallet.NewInMemoryWalletFromConfig(contractDeployerPrivateKeyHex, integration.ObscuroChainID, testlog.Logger()) + contractDeployerWallet := wallet.NewInMemoryWalletFromConfig(contractDeployerPrivateKeyHex, integration.TenChainID, testlog.Logger()) // We send more than enough to the contract deployer, to make sure prefunding won't be needed. excessivePrealloc := big.NewInt(contractdeployer.Prealloc * 3) testcommon.PrefundWallets(context.Background(), faucetWallet, obsclient.NewAuthObsClient(faucetClient), 0, []wallet.Wallet{contractDeployerWallet}, excessivePrealloc, receiptTimeout) @@ -106,7 +106,7 @@ func TestFaucetSendsFundsOnlyIfNeeded(t *testing.T) { NodePort: uint(startPort + integration.DefaultHostRPCWSOffset), IsL1Deployment: false, PrivateKey: contractDeployerPrivateKeyHex, - ChainID: big.NewInt(integration.ObscuroChainID), + ChainID: big.NewInt(integration.TenChainID), ContractName: contractdeployer.Layer2Erc20Contract, ConstructorParams: []string{erc20ParamOne, erc20ParamTwo, erc20ParamThree}, } @@ -133,7 +133,7 @@ func TestFaucetSendsFundsOnlyIfNeeded(t *testing.T) { func createObscuroNetwork(t *testing.T, startPort int) { // Create the Obscuro network. numberOfNodes := 1 - wallets := params.NewSimWallets(1, numberOfNodes, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(1, numberOfNodes, integration.EthereumChainID, integration.TenChainID) simParams := params.SimParams{ NumberOfNodes: numberOfNodes, AvgBlockDuration: 1 * time.Second, diff --git a/integration/faucet/faucet_test.go b/integration/faucet/faucet_test.go index a71826a515..f893510f51 100644 --- a/integration/faucet/faucet_test.go +++ b/integration/faucet/faucet_test.go @@ -52,7 +52,7 @@ func TestFaucet(t *testing.T) { HTTPPort: startPort + integration.DefaultHostRPCHTTPOffset, PK: "0x" + contractDeployerPrivateKeyHex, JWTSecret: "This_is_secret", - ChainID: big.NewInt(integration.ObscuroChainID), + ChainID: big.NewInt(integration.TenChainID), ServerPort: integration.StartPortFaucetHTTPUnitTest, DefaultFundAmount: new(big.Int).Mul(big.NewInt(100), big.NewInt(1e18)), } @@ -66,7 +66,7 @@ func TestFaucet(t *testing.T) { require.NoError(t, err) require.NotZero(t, initialFaucetBal) - rndWallet := datagenerator.RandomWallet(integration.ObscuroChainID) + rndWallet := datagenerator.RandomWallet(integration.TenChainID) err = fundWallet(faucetConfig.ServerPort, rndWallet) require.NoError(t, err) @@ -91,7 +91,7 @@ func TestFaucet(t *testing.T) { func createObscuroNetwork(t *testing.T, startPort int) { // Create the Obscuro network. numberOfNodes := 1 - wallets := params.NewSimWallets(1, numberOfNodes, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(1, numberOfNodes, integration.EthereumChainID, integration.TenChainID) simParams := params.SimParams{ NumberOfNodes: numberOfNodes, AvgBlockDuration: 1 * time.Second, diff --git a/integration/manualtests/connection_test.go b/integration/manualtests/connection_test.go index c307685c35..9935df547d 100644 --- a/integration/manualtests/connection_test.go +++ b/integration/manualtests/connection_test.go @@ -22,7 +22,7 @@ func TestSubscribeToOG(t *testing.T) { ogWSAddress := "wss://dev-testnet.obscu.ro:81" // ogWSAddress := "ws://51.132.131.47:81" - ogClient := lib.NewObscuroGatewayLibrary(ogHTTPAddress, ogWSAddress) + ogClient := lib.NewTenGatewayLibrary(ogHTTPAddress, ogWSAddress) // join the network err := ogClient.Join() diff --git a/integration/networktest/actions/setup_actions.go b/integration/networktest/actions/setup_actions.go index 9bef943c54..174a506403 100644 --- a/integration/networktest/actions/setup_actions.go +++ b/integration/networktest/actions/setup_actions.go @@ -21,7 +21,7 @@ func (c *CreateTestUser) String() string { func (c *CreateTestUser) Run(ctx context.Context, network networktest.NetworkConnector) (context.Context, error) { logger := testlog.Logger() - wal := datagenerator.RandomWallet(integration.ObscuroChainID) + wal := datagenerator.RandomWallet(integration.TenChainID) // traffic sim users are round robin-ed onto the validators for now (todo (@matt) - make that overridable) user := userwallet.NewUserWallet(wal.PrivateKey(), network.ValidatorRPCAddress(c.UserID%network.NumValidators()), logger) return storeTestUser(ctx, c.UserID, user), nil diff --git a/integration/networktest/env/testnet.go b/integration/networktest/env/testnet.go index 3f7001909a..7e0d9cb810 100644 --- a/integration/networktest/env/testnet.go +++ b/integration/networktest/env/testnet.go @@ -52,13 +52,13 @@ func NewTestnetConnectorWithFaucetAccount(seqRPCAddr string, validatorRPCAddress return &testnetConnector{ seqRPCAddress: seqRPCAddr, validatorRPCAddresses: validatorRPCAddressses, - faucetWallet: userwallet.NewUserWallet(ecdsaKey, validatorRPCAddressses[0], testlog.Logger(), userwallet.WithChainID(big.NewInt(integration.ObscuroChainID))), + faucetWallet: userwallet.NewUserWallet(ecdsaKey, validatorRPCAddressses[0], testlog.Logger(), userwallet.WithChainID(big.NewInt(integration.TenChainID))), l1RPCURL: l1RPCAddress, } } func (t *testnetConnector) ChainID() int64 { - return integration.ObscuroChainID + return integration.TenChainID } func (t *testnetConnector) AllocateFaucetFunds(ctx context.Context, account gethcommon.Address) error { diff --git a/integration/networktest/userwallet/userwallet.go b/integration/networktest/userwallet/userwallet.go index a1f2f8b2fb..aa580037b9 100644 --- a/integration/networktest/userwallet/userwallet.go +++ b/integration/networktest/userwallet/userwallet.go @@ -70,7 +70,7 @@ func NewUserWallet(pk *ecdsa.PrivateKey, rpcEndpoint string, logger gethlog.Logg privateKey: pk, publicKey: publicKeyECDSA, accountAddress: crypto.PubkeyToAddress(*publicKeyECDSA), - chainID: big.NewInt(integration.ObscuroChainID), // default, overridable using `WithChainID(...) opt` + chainID: big.NewInt(integration.TenChainID), // default, overridable using `WithChainID(...) opt` rpcEndpoint: rpcEndpoint, logger: logger, } @@ -82,7 +82,7 @@ func NewUserWallet(pk *ecdsa.PrivateKey, rpcEndpoint string, logger gethlog.Logg } func (s *UserWallet) ChainID() *big.Int { - return big.NewInt(integration.ObscuroChainID) + return big.NewInt(integration.TenChainID) } func (s *UserWallet) SendFunds(ctx context.Context, addr gethcommon.Address, value *big.Int, gas uint64) (*gethcommon.Hash, error) { diff --git a/integration/obscurogateway/gateway_user.go b/integration/obscurogateway/gateway_user.go index 9ea6fe699a..4820b32e97 100644 --- a/integration/obscurogateway/gateway_user.go +++ b/integration/obscurogateway/gateway_user.go @@ -16,11 +16,11 @@ type GatewayUser struct { Wallets []wallet.Wallet HTTPClient *ethclient.Client WSClient *ethclient.Client - ogClient *lib.OGLib + tgClient *lib.TGLib } func NewUser(wallets []wallet.Wallet, serverAddressHTTP string, serverAddressWS string) (*GatewayUser, error) { - ogClient := lib.NewObscuroGatewayLibrary(serverAddressHTTP, serverAddressWS) + ogClient := lib.NewTenGatewayLibrary(serverAddressHTTP, serverAddressWS) // automatically join err := ogClient.Join() @@ -29,11 +29,11 @@ func NewUser(wallets []wallet.Wallet, serverAddressHTTP string, serverAddressWS } // create clients - httpClient, err := ethclient.Dial(serverAddressHTTP + "/v1/" + "?u=" + ogClient.UserID()) + httpClient, err := ethclient.Dial(serverAddressHTTP + "/v1/" + "?token=" + ogClient.UserID()) if err != nil { return nil, err } - wsClient, err := ethclient.Dial(serverAddressWS + "/v1/" + "?u=" + ogClient.UserID()) + wsClient, err := ethclient.Dial(serverAddressWS + "/v1/" + "?token=" + ogClient.UserID()) if err != nil { return nil, err } @@ -42,17 +42,17 @@ func NewUser(wallets []wallet.Wallet, serverAddressHTTP string, serverAddressWS Wallets: wallets, HTTPClient: httpClient, WSClient: wsClient, - ogClient: ogClient, + tgClient: ogClient, }, nil } func (u GatewayUser) RegisterAccounts() error { for _, w := range u.Wallets { - err := u.ogClient.RegisterAccount(w.PrivateKey(), w.Address()) + err := u.tgClient.RegisterAccount(w.PrivateKey(), w.Address()) if err != nil { return err } - fmt.Printf("Successfully registered address %s for user: %s.\n", w.Address().Hex(), u.ogClient.UserID()) + fmt.Printf("Successfully registered address %s for user: %s.\n", w.Address().Hex(), u.tgClient.UserID()) } return nil diff --git a/integration/obscurogateway/obscurogateway_test.go b/integration/obscurogateway/tengateway_test.go similarity index 89% rename from integration/obscurogateway/obscurogateway_test.go rename to integration/obscurogateway/tengateway_test.go index 70091d1ac1..95c6a88ad0 100644 --- a/integration/obscurogateway/obscurogateway_test.go +++ b/integration/obscurogateway/tengateway_test.go @@ -40,24 +40,24 @@ import ( func init() { //nolint:gochecknoinits testlog.Setup(&testlog.Cfg{ LogDir: testLogs, - TestType: "obscurogateway", + TestType: "tengateway", TestSubtype: "test", LogLevel: log.LvlInfo, }) } const ( - testLogs = "../.build/obscurogateway/" + testLogs = "../.build/tengateway/" ) -func TestObscuroGateway(t *testing.T) { - startPort := integration.StartPortObscuroGatewayUnitTest - createObscuroNetwork(t, startPort) +func TestTenGateway(t *testing.T) { + startPort := integration.StartPortTenGatewayUnitTest + createTenNetwork(t, startPort) - obscuroGatewayConf := config.Config{ + tenGatewayConf := config.Config{ WalletExtensionHost: "127.0.0.1", - WalletExtensionPortHTTP: startPort + integration.DefaultObscuroGatewayHTTPPortOffset, - WalletExtensionPortWS: startPort + integration.DefaultObscuroGatewayWSPortOffset, + WalletExtensionPortHTTP: startPort + integration.DefaultTenGatewayHTTPPortOffset, + WalletExtensionPortWS: startPort + integration.DefaultTenGatewayWSPortOffset, NodeRPCHTTPAddress: fmt.Sprintf("127.0.0.1:%d", startPort+integration.DefaultHostRPCHTTPOffset), NodeRPCWebsocketAddress: fmt.Sprintf("127.0.0.1:%d", startPort+integration.DefaultHostRPCWSOffset), LogPath: "sys_out", @@ -66,9 +66,9 @@ func TestObscuroGateway(t *testing.T) { TenChainID: 443, } - obscuroGwContainer := container.NewWalletExtensionContainerFromConfig(obscuroGatewayConf, testlog.Logger()) + tenGwContainer := container.NewWalletExtensionContainerFromConfig(tenGatewayConf, testlog.Logger()) go func() { - err := obscuroGwContainer.Start() + err := tenGwContainer.Start() if err != nil { fmt.Printf("error stopping WE - %s", err) } @@ -78,15 +78,15 @@ func TestObscuroGateway(t *testing.T) { time.Sleep(5 * time.Second) // make sure the server is ready to receive requests - httpURL := fmt.Sprintf("http://%s:%d", obscuroGatewayConf.WalletExtensionHost, obscuroGatewayConf.WalletExtensionPortHTTP) - wsURL := fmt.Sprintf("ws://%s:%d", obscuroGatewayConf.WalletExtensionHost, obscuroGatewayConf.WalletExtensionPortWS) + httpURL := fmt.Sprintf("http://%s:%d", tenGatewayConf.WalletExtensionHost, tenGatewayConf.WalletExtensionPortHTTP) + wsURL := fmt.Sprintf("ws://%s:%d", tenGatewayConf.WalletExtensionHost, tenGatewayConf.WalletExtensionPortWS) // make sure the server is ready to receive requests err := waitServerIsReady(httpURL) require.NoError(t, err) // prefunded wallet - w := wallet.NewInMemoryWalletFromConfig(genesis.TestnetPrefundedPK, integration.ObscuroChainID, testlog.Logger()) + w := wallet.NewInMemoryWalletFromConfig(genesis.TestnetPrefundedPK, integration.TenChainID, testlog.Logger()) // run the tests against the exis for name, test := range map[string]func(*testing.T, string, string, wallet.Wallet){ @@ -103,22 +103,22 @@ func TestObscuroGateway(t *testing.T) { } // Gracefully shutdown - err = obscuroGwContainer.Stop() + err = tenGwContainer.Stop() assert.NoError(t, err) } func testMultipleAccountsSubscription(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { user0, err := NewUser([]wallet.Wallet{w}, httpURL, wsURL) require.NoError(t, err) - fmt.Printf("Created user with UserID: %s\n", user0.ogClient.UserID()) + fmt.Printf("Created user with encryption token: %s\n", user0.tgClient.UserID()) - user1, err := NewUser([]wallet.Wallet{datagenerator.RandomWallet(integration.ObscuroChainID), datagenerator.RandomWallet(integration.ObscuroChainID)}, httpURL, wsURL) + user1, err := NewUser([]wallet.Wallet{datagenerator.RandomWallet(integration.TenChainID), datagenerator.RandomWallet(integration.TenChainID)}, httpURL, wsURL) require.NoError(t, err) - fmt.Printf("Created user with UserID: %s\n", user0.ogClient.UserID()) + fmt.Printf("Created user with encryption token: %s\n", user0.tgClient.UserID()) - user2, err := NewUser([]wallet.Wallet{datagenerator.RandomWallet(integration.ObscuroChainID), datagenerator.RandomWallet(integration.ObscuroChainID)}, httpURL, wsURL) + user2, err := NewUser([]wallet.Wallet{datagenerator.RandomWallet(integration.TenChainID), datagenerator.RandomWallet(integration.TenChainID)}, httpURL, wsURL) require.NoError(t, err) - fmt.Printf("Created user with UserID: %s\n", user0.ogClient.UserID()) + fmt.Printf("Created user with encryption token: %s\n", user0.tgClient.UserID()) // register all the accounts for that user err = user0.RegisterAccounts() @@ -190,7 +190,7 @@ func testMultipleAccountsSubscription(t *testing.T, httpURL, wsURL string, w wal subscribeToEvents([]gethcommon.Address{contractReceipt.ContractAddress}, nil, user2.WSClient, &user2logs) // user1 calls setMessage and setMessage2 on deployed smart contract with the account - // that was registered as the first in OG + // that was registered as the first in TG user1MessageValue := "user1PublicEvent" // interact with smart contract and cause events to be emitted _, err = integrationCommon.InteractWithSmartContract(user1.HTTPClient, user1.Wallets[0], eventsContractABI, "setMessage", "user1PrivateEvent", contractReceipt.ContractAddress) @@ -211,7 +211,7 @@ func testMultipleAccountsSubscription(t *testing.T, httpURL, wsURL string, w wal assert.Equal(t, user1MessageValue, resultMessage) // user2 calls setMessage and setMessage2 on deployed smart contract with the account - // that was registered as the second in OG + // that was registered as the second in TG user2MessageValue := "user2PublicEvent" // interact with smart contract and cause events to be emitted _, err = integrationCommon.InteractWithSmartContract(user2.HTTPClient, user2.Wallets[1], eventsContractABI, "setMessage", "user2PrivateEvent", contractReceipt.ContractAddress) @@ -243,8 +243,8 @@ func testMultipleAccountsSubscription(t *testing.T, httpURL, wsURL string, w wal } func testAreTxsMinted(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { //nolint: unused - // set up the ogClient - ogClient := lib.NewObscuroGatewayLibrary(httpURL, wsURL) + // set up the tgClient + ogClient := lib.NewTenGatewayLibrary(httpURL, wsURL) // join + register against the og err := ogClient.Join() @@ -270,8 +270,8 @@ func testAreTxsMinted(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { // } func testErrorHandling(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { - // set up the ogClient - ogClient := lib.NewObscuroGatewayLibrary(httpURL, wsURL) + // set up the tgClient + ogClient := lib.NewTenGatewayLibrary(httpURL, wsURL) // join + register against the og err := ogClient.Join() @@ -301,7 +301,7 @@ func testErrorHandling(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { require.NoError(t, err) // repeat the process for the gateway - _, response, err = httputil.PostDataJSON(fmt.Sprintf("http://localhost:%d", integration.StartPortObscuroGatewayUnitTest), []byte(req)) + _, response, err = httputil.PostDataJSON(fmt.Sprintf("http://localhost:%d", integration.StartPortTenGatewayUnitTest), []byte(req)) require.NoError(t, err) // we only care about format @@ -312,8 +312,8 @@ func testErrorHandling(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { } func testErrorsRevertedArePassed(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { - // set up the ogClient - ogClient := lib.NewObscuroGatewayLibrary(httpURL, wsURL) + // set up the tgClient + ogClient := lib.NewTenGatewayLibrary(httpURL, wsURL) // join + register against the og err := ogClient.Join() @@ -388,9 +388,9 @@ func testErrorsRevertedArePassed(t *testing.T, httpURL, wsURL string, w wallet.W func testUnsubscribe(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { // create a user with multiple accounts - user, err := NewUser([]wallet.Wallet{w, datagenerator.RandomWallet(integration.ObscuroChainID)}, httpURL, wsURL) + user, err := NewUser([]wallet.Wallet{w, datagenerator.RandomWallet(integration.TenChainID)}, httpURL, wsURL) require.NoError(t, err) - fmt.Printf("Created user with UserID: %s\n", user.ogClient.UserID()) + fmt.Printf("Created user with encryption token: %s\n", user.tgClient.UserID()) // register all the accounts for the user err = user.RegisterAccounts() @@ -438,9 +438,9 @@ func testUnsubscribe(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { func testClosingConnectionWhileSubscribed(t *testing.T, httpURL, wsURL string, w wallet.Wallet) { // create a user with multiple accounts - user, err := NewUser([]wallet.Wallet{w, datagenerator.RandomWallet(integration.ObscuroChainID)}, httpURL, wsURL) + user, err := NewUser([]wallet.Wallet{w, datagenerator.RandomWallet(integration.TenChainID)}, httpURL, wsURL) require.NoError(t, err) - fmt.Printf("Created user with UserID: %s\n", user.ogClient.UserID()) + fmt.Printf("Created user with encryption token: %s\n", user.tgClient.UserID()) // register all the accounts for the user err = user.RegisterAccounts() @@ -479,7 +479,7 @@ func testClosingConnectionWhileSubscribed(t *testing.T, httpURL, wsURL string, w assert.Equal(t, 0, len(userLogs)) // re-establish connection - wsClient, err := ethclient.Dial(wsURL + "/v1/" + "?u=" + user.ogClient.UserID()) + wsClient, err := ethclient.Dial(wsURL + "/v1/" + "?token=" + user.tgClient.UserID()) require.NoError(t, err) user.WSClient = wsClient @@ -525,11 +525,11 @@ func transferRandomAddr(t *testing.T, client *ethclient.Client, w wallet.Wallet) return signedTx.Hash() } -// Creates a single-node Obscuro network for testing. -func createObscuroNetwork(t *testing.T, startPort int) { - // Create the Obscuro network. +// Creates a single-node Ten network for testing. +func createTenNetwork(t *testing.T, startPort int) { + // Create the Ten network. numberOfNodes := 1 - wallets := params.NewSimWallets(1, numberOfNodes, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(1, numberOfNodes, integration.EthereumChainID, integration.TenChainID) simParams := params.SimParams{ NumberOfNodes: numberOfNodes, AvgBlockDuration: 1 * time.Second, @@ -540,11 +540,11 @@ func createObscuroNetwork(t *testing.T, startPort int) { WithPrefunding: true, } - obscuroNetwork := network.NewNetworkOfSocketNodes(wallets) - t.Cleanup(obscuroNetwork.TearDown) - _, err := obscuroNetwork.Create(&simParams, nil) + tenNetwork := network.NewNetworkOfSocketNodes(wallets) + t.Cleanup(tenNetwork.TearDown) + _, err := tenNetwork.Create(&simParams, nil) if err != nil { - panic(fmt.Sprintf("failed to create test Obscuro network. Cause: %s", err)) + panic(fmt.Sprintf("failed to create test Ten network. Cause: %s", err)) } } diff --git a/integration/obscuroscan/obscuroscan_test.go b/integration/obscuroscan/obscuroscan_test.go index b8feb958fe..a6424866e1 100644 --- a/integration/obscuroscan/obscuroscan_test.go +++ b/integration/obscuroscan/obscuroscan_test.go @@ -47,12 +47,12 @@ const ( ) func TestObscuroscan(t *testing.T) { - startPort := integration.StartPortObscuroscanUnitTest + startPort := integration.StartPortTenscanUnitTest createObscuroNetwork(t, startPort) obsScanConfig := &config.Config{ NodeHostAddress: fmt.Sprintf("http://127.0.0.1:%d", startPort+integration.DefaultHostRPCHTTPOffset), - ServerAddress: fmt.Sprintf("127.0.0.1:%d", startPort+integration.DefaultObscuroscanHTTPPortOffset), + ServerAddress: fmt.Sprintf("127.0.0.1:%d", startPort+integration.DefaultTenscanHTTPPortOffset), LogPath: "sys_out", } serverAddress := fmt.Sprintf("http://%s", obsScanConfig.ServerAddress) @@ -73,7 +73,7 @@ func TestObscuroscan(t *testing.T) { issueTransactions( t, fmt.Sprintf("ws://127.0.0.1:%d", startPort+integration.DefaultHostRPCWSOffset), - wallet.NewInMemoryWalletFromConfig(genesis.TestnetPrefundedPK, integration.ObscuroChainID, testlog.Logger()), + wallet.NewInMemoryWalletFromConfig(genesis.TestnetPrefundedPK, integration.TenChainID, testlog.Logger()), 5, ) @@ -203,7 +203,7 @@ func waitServerIsReady(serverAddr string) error { // Creates a single-node Obscuro network for testing. func createObscuroNetwork(t *testing.T, startPort int) { // Create the Obscuro network. - wallets := params.NewSimWallets(1, 1, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(1, 1, integration.EthereumChainID, integration.TenChainID) simParams := params.SimParams{ NumberOfNodes: 1, AvgBlockDuration: 1 * time.Second, diff --git a/integration/simulation/devnetwork/config.go b/integration/simulation/devnetwork/config.go index 140577b469..51a4998a5c 100644 --- a/integration/simulation/devnetwork/config.go +++ b/integration/simulation/devnetwork/config.go @@ -38,7 +38,7 @@ type ObscuroConfig struct { // DefaultDevNetwork provides an off-the-shelf default config for a sim network func DefaultDevNetwork() *InMemDevNetwork { numNodes := 4 // Default sim currently uses 4 L1 nodes. Obscuro nodes: 1 seq, 3 validators - networkWallets := params.NewSimWallets(0, numNodes, integration.EthereumChainID, integration.ObscuroChainID) + networkWallets := params.NewSimWallets(0, numNodes, integration.EthereumChainID, integration.TenChainID) l1Config := &L1Config{ PortStart: integration.StartPortSimulationFullNetwork, NumNodes: 4, @@ -71,7 +71,7 @@ func LiveL1DevNetwork(seqWallet wallet.Wallet, validatorWallets []wallet.Wallet, if err != nil { panic("could not initialise L2 faucet private key") } - l2FaucetWallet := wallet.NewInMemoryWalletFromPK(big.NewInt(integration.ObscuroChainID), l2FaucetPrivKey, testlog.Logger()) + l2FaucetWallet := wallet.NewInMemoryWalletFromPK(big.NewInt(integration.TenChainID), l2FaucetPrivKey, testlog.Logger()) networkWallets := ¶ms.SimWallets{ MCOwnerWallet: seqWallet, NodeWallets: append([]wallet.Wallet{seqWallet}, validatorWallets...), diff --git a/integration/simulation/devnetwork/dev_network.go b/integration/simulation/devnetwork/dev_network.go index 462bc26feb..ea85e7ed5d 100644 --- a/integration/simulation/devnetwork/dev_network.go +++ b/integration/simulation/devnetwork/dev_network.go @@ -59,7 +59,7 @@ func (s *InMemDevNetwork) GetMCOwnerWallet() (wallet.Wallet, error) { } func (s *InMemDevNetwork) ChainID() int64 { - return integration.ObscuroChainID + return integration.TenChainID } func (s *InMemDevNetwork) FaucetWallet() wallet.Wallet { diff --git a/integration/simulation/devnetwork/node.go b/integration/simulation/devnetwork/node.go index 071d2eb425..60e70c2dca 100644 --- a/integration/simulation/devnetwork/node.go +++ b/integration/simulation/devnetwork/node.go @@ -123,7 +123,7 @@ func (n *InMemNodeOperator) createHostContainer() *hostcontainer.HostContainer { ManagementContractAddress: n.l1Data.MgmtContractAddress, MessageBusAddress: n.l1Data.MessageBusAddr, L1ChainID: integration.EthereumChainID, - ObscuroChainID: integration.ObscuroChainID, + ObscuroChainID: integration.TenChainID, L1StartHash: n.l1Data.ObscuroStartBlock, SequencerID: n.config.SequencerID, UseInMemoryDB: false, @@ -167,7 +167,7 @@ func (n *InMemNodeOperator) createEnclaveContainer() *enclavecontainer.EnclaveCo Address: enclaveAddr, NodeType: n.nodeType, L1ChainID: integration.EthereumChainID, - ObscuroChainID: integration.ObscuroChainID, + ObscuroChainID: integration.TenChainID, ValidateL1Blocks: false, WillAttest: false, GenesisJSON: nil, diff --git a/integration/simulation/network/network_utils.go b/integration/simulation/network/network_utils.go index 399ea5668d..4633975fea 100644 --- a/integration/simulation/network/network_utils.go +++ b/integration/simulation/network/network_utils.go @@ -83,7 +83,7 @@ func createInMemObscuroNode( HostID: hostConfig.ID, NodeType: nodeType, L1ChainID: integration.EthereumChainID, - ObscuroChainID: integration.ObscuroChainID, + ObscuroChainID: integration.TenChainID, WillAttest: false, ValidateL1Blocks: validateBlocks, GenesisJSON: genesisJSON, diff --git a/integration/simulation/simulation_full_network_test.go b/integration/simulation/simulation_full_network_test.go index 3f56a64d66..926f736cd8 100644 --- a/integration/simulation/simulation_full_network_test.go +++ b/integration/simulation/simulation_full_network_test.go @@ -20,7 +20,7 @@ func TestFullNetworkMonteCarloSimulation(t *testing.T) { numberOfNodes := 5 numberOfSimWallets := 5 - wallets := params.NewSimWallets(numberOfSimWallets, numberOfNodes, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(numberOfSimWallets, numberOfNodes, integration.EthereumChainID, integration.TenChainID) simParams := ¶ms.SimParams{ NumberOfNodes: numberOfNodes, diff --git a/integration/simulation/simulation_geth_in_mem_test.go b/integration/simulation/simulation_geth_in_mem_test.go index 4c59b81f04..6f24453691 100644 --- a/integration/simulation/simulation_geth_in_mem_test.go +++ b/integration/simulation/simulation_geth_in_mem_test.go @@ -23,7 +23,7 @@ func TestGethSimulation(t *testing.T) { numberOfNodes := 5 numberOfSimWallets := 5 - wallets := params.NewSimWallets(numberOfSimWallets, numberOfNodes, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(numberOfSimWallets, numberOfNodes, integration.EthereumChainID, integration.TenChainID) simParams := ¶ms.SimParams{ NumberOfNodes: numberOfNodes, diff --git a/integration/simulation/simulation_in_mem_test.go b/integration/simulation/simulation_in_mem_test.go index c776360021..b29f057ab5 100644 --- a/integration/simulation/simulation_in_mem_test.go +++ b/integration/simulation/simulation_in_mem_test.go @@ -21,7 +21,7 @@ func TestInMemoryMonteCarloSimulation(t *testing.T) { // todo (#718) - try increasing this back to 7 once faster-finality model is optimised numberOfNodes := 5 numberOfSimWallets := 10 - wallets := params.NewSimWallets(numberOfSimWallets, numberOfNodes, integration.EthereumChainID, integration.ObscuroChainID) + wallets := params.NewSimWallets(numberOfSimWallets, numberOfNodes, integration.EthereumChainID, integration.TenChainID) simParams := params.SimParams{ NumberOfNodes: numberOfNodes, diff --git a/tools/gateway-js/gateway-lib/gateway.js b/tools/gateway-js/gateway-lib/gateway.js index 933355c6af..8d997dfe9e 100644 --- a/tools/gateway-js/gateway-lib/gateway.js +++ b/tools/gateway-js/gateway-lib/gateway.js @@ -44,7 +44,7 @@ class Gateway { } try { - const authenticateUserURL = pathAuthenticate+"?u="+this.userId + const authenticateUserURL = pathAuthenticate+"?token="+this.userId const authenticateFields = {"signature": signature, "message": message} const authenticateResp = await axios.post( authenticateUserURL, @@ -68,11 +68,11 @@ class Gateway { } http() { - return `${this.httpURL}/v1/?u=${this.userId}`; + return `${this.httpURL}/v1/?token=${this.userId}`; } ws() { - return `${this.wsURL}/v1/?u=${this.userId}`; + return `${this.wsURL}/v1/?token=${this.userId}`; } } diff --git a/tools/walletextension/README.md b/tools/walletextension/README.md index 0074b295bf..c7ef89fe32 100644 --- a/tools/walletextension/README.md +++ b/tools/walletextension/README.md @@ -38,16 +38,16 @@ For interacting with Ten Gateway, there are the following HTTP endpoints availab It generates and returns userID which needs to be added as a query parameter "u" to the URL in your Metamask (or another provider) as it identifies you. -- `POST /v1/authenticate?u=$UserId` +- `POST /v1/authenticate?token=$EncryptionToken` With this endpoint, you submit a signed message in the format `Register for ` from that account which proves that you hold private keys for it, and it links that account with your userID. -- `GET /v1/query/address?u=$UserId&a=$Address` +- `GET /v1/query/address?token=$EncryptionToken&a=$Address` This endpoint responds with a JSON of true or false if the address "a" is already registered for user "u" -- `POST "/v1/revoke?u=$UserId"` +- `POST "/v1/revoke?token=$EncryptionToken"` When this endpoint is triggered, the userId with the authenticated viewing keys should be deleted. diff --git a/tools/walletextension/api/staticOG/javascript.js b/tools/walletextension/api/staticOG/javascript.js index 69e869d078..51db8aec41 100644 --- a/tools/walletextension/api/staticOG/javascript.js +++ b/tools/walletextension/api/staticOG/javascript.js @@ -105,7 +105,7 @@ async function addNetworkToMetaMask(ethereum, userID, chainIDDecimal) { getRPCFromUrl(obscuroGatewayAddress) + "/" + obscuroGatewayVersion + - "/?u=" + + "/?token=" + userID, ], blockExplorerUrls: ["https://testnet.obscuroscan.io"], @@ -158,7 +158,7 @@ async function authenticateAccountWithObscuroGatewayEIP712(ethereum, account, us }); - const authenticateUserURL = pathAuthenticate+"?u="+userID + const authenticateUserURL = pathAuthenticate+"?token="+userID const authenticateFields = {"signature": signature, "address": account } const authenticateResp = await fetch( authenticateUserURL, { @@ -172,7 +172,7 @@ async function authenticateAccountWithObscuroGatewayEIP712(ethereum, account, us async function accountIsAuthenticated(account, userID) { - const queryAccountUserID = pathQuery + "?u=" + userID + "&a=" + account; + const queryAccountUserID = pathQuery + "?token=" + userID + "&a=" + account; const isAuthenticatedResponse = await fetch(queryAccountUserID, { method: methodGet, headers: jsonHeaders, @@ -183,7 +183,7 @@ async function accountIsAuthenticated(account, userID) { } async function revokeUserID(userID) { - const queryAccountUserID = pathRevoke + "?u=" + userID; + const queryAccountUserID = pathRevoke + "?token=" + userID; const revokeResponse = await fetch(queryAccountUserID, { method: methodGet, headers: jsonHeaders, diff --git a/tools/walletextension/api/utils.go b/tools/walletextension/api/utils.go index bd5eb96031..96f14038fa 100644 --- a/tools/walletextension/api/utils.go +++ b/tools/walletextension/api/utils.go @@ -51,9 +51,21 @@ func getQueryParameter(params map[string]string, selectedParameter string) (stri return value, nil } +// getUserID returns userID from query params / url of the URL +// it always first tries to get userID from a query parameter `u` or `token` (`u` parameter will become deprecated) +// if it fails to get userID from a query parameter it tries to get it from the URL and it needs position as the second parameter func getUserID(conn userconn.UserConn, userIDPosition int) (string, error) { - // try getting userID from query parameters and return it if successful - userID, err := getQueryParameter(conn.ReadRequestParams(), common.UserQueryParameter) + // try getting userID (`token`) from query parameters and return it if successful + userID, err := getQueryParameter(conn.ReadRequestParams(), common.EncryptedTokenQueryParameter) + if err == nil { + if len(userID) != common.MessageUserIDLen { + return "", fmt.Errorf(fmt.Sprintf("wrong length of userID from URL. Got: %d, Expected: %d", len(userID), common.MessageUserIDLen)) + } + return userID, err + } + + // try getting userID(`u`) from query parameters and return it if successful + userID, err = getQueryParameter(conn.ReadRequestParams(), common.UserQueryParameter) if err == nil { if len(userID) != common.MessageUserIDLen { return "", fmt.Errorf(fmt.Sprintf("wrong length of userID from URL. Got: %d, Expected: %d", len(userID), common.MessageUserIDLen)) diff --git a/tools/walletextension/common/constants.go b/tools/walletextension/common/constants.go index ee62e18742..6cca9175e0 100644 --- a/tools/walletextension/common/constants.go +++ b/tools/walletextension/common/constants.go @@ -38,12 +38,10 @@ const ( WSProtocol = "ws://" DefaultUser = "defaultUser" UserQueryParameter = "u" + EncryptedTokenQueryParameter = "token" AddressQueryParameter = "a" - MessageFormatRegex = `^Register\s(\w+)\sfor\s(\w+)$` MessageUserIDLen = 40 - SignatureLen = 65 EthereumAddressLen = 42 - PersonalSignMessagePrefix = "\x19Ethereum Signed Message:\n%d%s" GetStorageAtUserIDRequestMethodName = "getUserID" SuccessMsg = "success" APIVersion1 = "/v1" diff --git a/tools/walletextension/lib/client_lib.go b/tools/walletextension/lib/client_lib.go index be93d990ec..e79aa305d4 100644 --- a/tools/walletextension/lib/client_lib.go +++ b/tools/walletextension/lib/client_lib.go @@ -17,24 +17,24 @@ import ( "github.com/valyala/fasthttp" ) -type OGLib struct { +type TGLib struct { httpURL string wsURL string userID []byte } -func NewObscuroGatewayLibrary(httpURL, wsURL string) *OGLib { - return &OGLib{ +func NewTenGatewayLibrary(httpURL, wsURL string) *TGLib { + return &TGLib{ httpURL: httpURL, wsURL: wsURL, } } -func (o *OGLib) UserID() string { +func (o *TGLib) UserID() string { return string(o.userID) } -func (o *OGLib) Join() error { +func (o *TGLib) Join() error { // todo move this to stdlib statusCode, userID, err := fasthttp.Get(nil, fmt.Sprintf("%s/v1/join/", o.httpURL)) if err != nil || statusCode != 200 { @@ -44,9 +44,9 @@ func (o *OGLib) Join() error { return nil } -func (o *OGLib) RegisterAccount(pk *ecdsa.PrivateKey, addr gethcommon.Address) error { +func (o *TGLib) RegisterAccount(pk *ecdsa.PrivateKey, addr gethcommon.Address) error { // create the registration message - rawMessage, err := viewingkey.GenerateAuthenticationEIP712RawData(string(o.userID), integration.ObscuroChainID) + rawMessage, err := viewingkey.GenerateAuthenticationEIP712RawData(string(o.userID), integration.TenChainID) if err != nil { return err } @@ -64,7 +64,7 @@ func (o *OGLib) RegisterAccount(pk *ecdsa.PrivateKey, addr gethcommon.Address) e req, err := http.NewRequestWithContext( context.Background(), http.MethodPost, - o.httpURL+"/v1/authenticate/?u="+string(o.userID), + o.httpURL+"/v1/authenticate/?token="+string(o.userID), strings.NewReader(payload), ) if err != nil { @@ -90,10 +90,10 @@ func (o *OGLib) RegisterAccount(pk *ecdsa.PrivateKey, addr gethcommon.Address) e return nil } -func (o *OGLib) HTTP() string { - return fmt.Sprintf("%s/v1/?u=%s", o.httpURL, o.userID) +func (o *TGLib) HTTP() string { + return fmt.Sprintf("%s/v1/?token=%s", o.httpURL, o.userID) } -func (o *OGLib) WS() string { - return fmt.Sprintf("%s/v1/?u=%s", o.wsURL, o.userID) +func (o *TGLib) WS() string { + return fmt.Sprintf("%s/v1/?token=%s", o.wsURL, o.userID) } diff --git a/tools/walletextension/test/utils.go b/tools/walletextension/test/utils.go index b56b53cb3c..7c5d2420cd 100644 --- a/tools/walletextension/test/utils.go +++ b/tools/walletextension/test/utils.go @@ -126,7 +126,7 @@ func makeHTTPEthJSONReqWithPath(port int, path string) []byte { // Makes an Ethereum JSON RPC request over HTTP and returns the response body with userID query paremeter. func makeHTTPEthJSONReqWithUserID(port int, method string, params interface{}, userID string) []byte { //nolint: unparam reqBody := prepareRequestBody(method, params) - return makeRequestHTTP(fmt.Sprintf("http://%s:%d/v1/?u=%s", common.Localhost, port, userID), reqBody) + return makeRequestHTTP(fmt.Sprintf("http://%s:%d/v1/?token=%s", common.Localhost, port, userID), reqBody) } // Makes an Ethereum JSON RPC request over websockets and returns the response body.