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

Preparation for subscribing with multiple accounts and test that confirms current issues #1516

Merged
merged 9 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
31 changes: 31 additions & 0 deletions integration/obscurogateway/events_contract.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// SPDX-License-Identifier: MIT
// Specify the Solidity version
pragma solidity ^0.8.0;

contract SimpleMessageContract {

// State variable to store the message
string public message;
string public message2;

// Event declaration
event MessageUpdatedWithAddress(string newMessage, address indexed sender);
event Message2Updated(string newMessage);

// Constructor to initialize the message
constructor() {
message = "foo";
message2 = "foo";
}

// Function to set a new message
function setMessage(string memory newMessage) public {
message = newMessage;
emit MessageUpdatedWithAddress(newMessage, msg.sender); // Emit the event (only sender can see it)
}

function setMessage2(string memory newMessage) public {
message2 = newMessage;
emit Message2Updated(newMessage); // Emit the event (everyone can see it)
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The previous comment about adding an onlyOwner modifier to restrict access to the setMessage and setMessage2 functions still stands. This is a security concern as currently, any address can call these functions and change the state variables message and message2. If you want to restrict this to only the contract owner or certain addresses, you should add a modifier to check the sender's address.

Here is the suggested change:

+   address public owner;
+   
+   modifier onlyOwner {
+       require(msg.sender == owner, "Only the contract owner can call this function");
+       _;
+   }
+   
    constructor() {
+       owner = msg.sender;
        message = "foo";
        message2 = "foo";
    }

    function setMessage(string memory newMessage) public onlyOwner {
        message = newMessage;
        emit MessageUpdatedWithAddress(newMessage, msg.sender);  // Emit the event (only sender can see it)
    }

    function setMessage2(string memory newMessage) public onlyOwner {
        message2 = newMessage;
        emit Message2Updated(newMessage);  // Emit the event (everyone can see it)
    }
Committable suggestion (Beta)
Suggested change
// SPDX-License-Identifier: MIT
// Specify the Solidity version
pragma solidity ^0.8.0;
contract SimpleMessageContract {
// State variable to store the message
string public message;
string public message2;
// Event declaration
event MessageUpdatedWithAddress(string newMessage, address indexed sender);
event Message2Updated(string newMessage);
// Constructor to initialize the message
constructor() {
message = "foo";
message2 = "foo";
}
// Function to set a new message
function setMessage(string memory newMessage) public {
message = newMessage;
emit MessageUpdatedWithAddress(newMessage, msg.sender); // Emit the event (only sender can see it)
}
function setMessage2(string memory newMessage) public {
message2 = newMessage;
emit Message2Updated(newMessage); // Emit the event (everyone can see it)
}
}
// SPDX-License-Identifier: MIT
// Specify the Solidity version
pragma solidity ^0.8.0;
contract SimpleMessageContract {
// State variable to store the message
string public message;
string public message2;
// Owner of the contract
address public owner;
// Event declaration
event MessageUpdatedWithAddress(string newMessage, address indexed sender);
event Message2Updated(string newMessage);
// Modifier to restrict access to owner only
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner can call this function");
_;
}
// Constructor to initialize the message
constructor() {
owner = msg.sender;
message = "foo";
message2 = "foo";
}
// Function to set a new message
function setMessage(string memory newMessage) public onlyOwner {
message = newMessage;
emit MessageUpdatedWithAddress(newMessage, msg.sender); // Emit the event (only sender can see it)
}
function setMessage2(string memory newMessage) public onlyOwner {
message2 = newMessage;
emit Message2Updated(newMessage); // Emit the event (everyone can see it)
}
}

121 changes: 121 additions & 0 deletions integration/obscurogateway/gateway_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package faucet

import (
"context"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"io"
"net/http"
"strings"

"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/obscuronet/go-obscuro/go/wallet"
"github.com/valyala/fasthttp"
)

type GatewayUser struct {
zkokelj marked this conversation as resolved.
Show resolved Hide resolved
UserID string
Wallets []wallet.Wallet
HTTPClient *ethclient.Client
WSClient *ethclient.Client
ServerAddressHTTP string
ServerAddressWS string
}

func NewUser(wallets []wallet.Wallet, serverAddressHTTP string, serverAddressWS string) (*GatewayUser, error) {
// automatically join OG
userID, err := joinObscuroGateway(serverAddressHTTP)
if err != nil {
return nil, err
}
zkokelj marked this conversation as resolved.
Show resolved Hide resolved

// create clients
httpClient, err := ethclient.Dial(serverAddressHTTP + "/v1/" + "?u=" + userID)
if err != nil {
return nil, err
}
wsClient, err := ethclient.Dial(serverAddressWS + "/v1/" + "?u=" + userID)
if err != nil {
return nil, err
}

return &GatewayUser{
UserID: userID,
Wallets: wallets,
HTTPClient: httpClient,
WSClient: wsClient,
ServerAddressHTTP: serverAddressHTTP,
ServerAddressWS: serverAddressWS,
}, nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The NewUser function creates a new user and initializes the HTTP and WebSocket clients. However, it does not validate the server addresses before using them. This could lead to unexpected behavior or errors when trying to dial the server. Consider validating the server addresses before using them.

+ _, err := url.ParseRequestURI(serverAddressHTTP)
+ if err != nil {
+     return nil, fmt.Errorf("invalid HTTP server address: %v", err)
+ }
+ _, err = url.ParseRequestURI(serverAddressWS)
+ if err != nil {
+     return nil, fmt.Errorf("invalid WebSocket server address: %v", err)
+ }


Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The NewUser function creates HTTP and WebSocket clients for the user. However, it does not check if the server addresses provided are valid URLs. This could lead to unexpected behavior or errors when trying to dial the server. Consider validating the server addresses before using them.

+    _, err := url.ParseRequestURI(serverAddressHTTP)
+    if err != nil {
+        return nil, fmt.Errorf("invalid HTTP server address: %v", err)
+    }
+    _, err = url.ParseRequestURI(serverAddressWS)
+    if err != nil {
+        return nil, fmt.Errorf("invalid WebSocket server address: %v", err)
+    }

func (u GatewayUser) RegisterAccounts() error {
for _, w := range u.Wallets {
response, err := registerAccount(u.ServerAddressHTTP, u.UserID, w.PrivateKey(), w.Address().Hex())
if err != nil {
return err
}
fmt.Printf("Successfully registered address %s for user: %s with response: %s \n", w.Address().Hex(), u.UserID, response)
}

return nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The RegisterAccounts function registers each wallet in the user's wallet list. However, if the registration of one account fails, the function returns an error immediately and does not attempt to register the remaining accounts. Consider continuing to register the remaining accounts and returning a list of errors instead.

+ var errs []error
+ for _, w := range u.Wallets {
+     response, err := registerAccount(u.ServerAddressHTTP, u.UserID, w.PrivateKey(), w.Address().Hex())
+     if err != nil {
+         errs = append(errs, err)
+         continue
+     }
+     fmt.Printf("Successfully registered address %s for user: %s with response: %s \n", w.Address().Hex(), u.UserID, response)
+ }
+ if len(errs) > 0 {
+     return fmt.Errorf("errors occurred during registration: %v", errs)
+ }
+ return nil


Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The RegisterAccounts function registers each wallet in the user's wallet list. However, if the registration of one account fails, the function returns an error immediately and does not attempt to register the remaining accounts. Consider continuing to register the remaining accounts and returning a list of errors instead.

+    var errs []error
+    for _, w := range u.Wallets {
+        response, err := registerAccount(u.ServerAddressHTTP, u.UserID, w.PrivateKey(), w.Address().Hex())
+        if err != nil {
+            errs = append(errs, err)
+            continue
+        }
+        fmt.Printf("Successfully registered address %s for user: %s with response: %s \n", w.Address().Hex(), u.UserID, response)
+    }
+    if len(errs) > 0 {
+        return fmt.Errorf("errors occurred during registration: %v", errs)
+    }
+    return nil

func (u GatewayUser) PrintUserAccountsBalances() error {
for _, w := range u.Wallets {
balance, err := u.HTTPClient.BalanceAt(context.Background(), w.Address(), nil)
if err != nil {
return err
}
fmt.Println("Balance for account ", w.Address().Hex(), " - ", balance.String())
}
return nil
}
Comment on lines +61 to +70
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As per the previous comment, the PrintUserAccountsBalances function is directly printing the balance of each account to the console. This might not be desirable in a production environment. Consider returning the balances to the caller instead, so they can decide how to handle it.

-		fmt.Println("Balance for account ", w.Address().Hex(), " - ", balance.String())
+		balances = append(balances, balance.String())
Committable suggestion (Beta)
Suggested change
func (u GatewayUser) PrintUserAccountsBalances() error {
for _, w := range u.Wallets {
balance, err := u.HTTPClient.BalanceAt(context.Background(), w.Address(), nil)
if err != nil {
return err
}
fmt.Println("Balance for account ", w.Address().Hex(), " - ", balance.String())
}
return nil
}
func (u GatewayUser) GetUserAccountsBalances() ([]string, error) {
balances := []string{}
for _, w := range u.Wallets {
balance, err := u.HTTPClient.BalanceAt(context.Background(), w.Address(), nil)
if err != nil {
return nil, err
}
balances = append(balances, balance.String())
}
return balances, nil
}


Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PrintUserAccountsBalances function is directly printing the balance of each account to the console. This might not be desirable in a production environment. Consider returning the balances to the caller instead, so they can decide how to handle it.

func registerAccount(url string, userID string, pk *ecdsa.PrivateKey, hexAddress string) ([]byte, error) {
payload := prepareRegisterPayload(userID, pk, hexAddress)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use the oglib here too.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed.


req, err := http.NewRequestWithContext(
context.Background(),
http.MethodPost,
url+"/v1/authenticate/?u="+userID,
strings.NewReader(payload),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=UTF-8")

client := &http.Client{}
response, err := client.Do(req)
if err != nil {
return nil, err
}

defer response.Body.Close()
return io.ReadAll(response.Body)
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The registerAccount function creates a new HTTP client for each registration request. This could lead to a large number of idle connections if many accounts are being registered. Consider reusing a single HTTP client for all requests.

-    client := &http.Client{}
+    client := http.DefaultClient

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The registerAccount function creates a new HTTP client for each registration request. This could lead to a large number of idle connections if many accounts are being registered. Consider reusing a single HTTP client for all requests.

- client := &http.Client{}
+ client := http.DefaultClient


Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The registerAccount function is creating a new HTTP client for each request. This could lead to a large number of idle connections if many requests are made. Consider reusing the same HTTP client for all requests.

-    client := &http.Client{}
+    client := http.DefaultClient

func prepareRegisterPayload(userID string, pk *ecdsa.PrivateKey, hexAddress string) string {
message := fmt.Sprintf("Register %s for %s", userID, strings.ToLower(hexAddress))
prefixedMessage := fmt.Sprintf("\u0019Ethereum Signed Message:\n%d%s", len(message), message)
messageHash := crypto.Keccak256([]byte(prefixedMessage))
sig, err := crypto.Sign(messageHash, pk)
if err != nil {
fmt.Printf("Failed to sign message: %v\n", err)
}
sig[64] += 27
signature := "0x" + hex.EncodeToString(sig)
payload := fmt.Sprintf("{\"signature\": \"%s\", \"message\": \"%s\"}", signature, message)
return payload
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The prepareRegisterPayload function does not handle the error from crypto.Sign. If an error occurs during signing, the function will continue to execute and may produce an invalid signature. Consider handling this error.

- if err != nil {
-     fmt.Printf("Failed to sign message: %v\n", err)
- }
+ if err != nil {
+     return "", fmt.Errorf("failed to sign message: %v", err)
+ }


Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The prepareRegisterPayload function does not handle the error from crypto.Sign. If an error occurs during signing, the function will continue to execute and may produce an invalid signature. Consider handling this error.

-    if err != nil {
-        fmt.Printf("Failed to sign message: %v\n", err)
-    }
+    if err != nil {
+        return "", fmt.Errorf("failed to sign message: %v", err)
+    }

func joinObscuroGateway(url string) (string, error) {
statusCode, userID, err := fasthttp.Get(nil, fmt.Sprintf("%s/v1/join/", url))
if err != nil || statusCode != 200 {
return "", fmt.Errorf(fmt.Sprintf("Failed to get userID. Status code: %d, err: %s", statusCode, err))
}
return string(userID), nil
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The joinObscuroGateway function is not handling non-200 status codes correctly. If the status code is not 200, it will still attempt to return the user ID, which could lead to unexpected behavior. Consider handling non-200 status codes separately.

- if err != nil || statusCode != 200 {
-     return "", fmt.Errorf(fmt.Sprintf("Failed to get userID. Status code: %d, err: %s", statusCode, err))
- }
- return string(userID), nil
+ if err != nil {
+     return "", fmt.Errorf("Failed to get userID: %v", err)
+ }
+ if statusCode != 200 {
+     return "", fmt.Errorf("Failed to get userID. Status code: %d", statusCode)
+ }
+ return string(userID), nil

Loading
Loading