yeagerai / genlayer-simulator

MIT License
8 stars 2 forks source link

SIM-Add signatures to transactions #236

Open cristiam86 opened 3 days ago

cristiam86 commented 3 days ago

General Info

This feature includes the refactoring of the send_transaction endpoint to be used to deploy and call contract functions. The endpoints call_contract_function and deploy_intelligent_contract will be deprecated (not removed for backwards compatibility).

Implementation plan

Note: the code provided are just examples.

1. Account Generation in the Frontend

Library Selection: Use ethers.js for key pair generation. Key Pair Generation:

const { ethers } = require('ethers');

// Generate a new key pair
const wallet = ethers.Wallet.createRandom();
const privateKey = wallet.privateKey;
const publicKey = wallet.address;

// Store the keys in the front-end account store

2. Transaction Signing in the Frontend

Sign Transaction:

const { ethers } = require('ethers');

async function signTransaction(transactionData) {
  const privateKey = localStorage.getItem('privateKey');
  const wallet = new ethers.Wallet(privateKey);

  // Create and sign the transaction
  const transaction = await wallet.signTransaction(transactionData);
}

3. Verify Signature in the Backend (Python)

Library Selection: Use eth-account.

from eth_account import Account
from eth_account.messages import encode_defunct
from web3 import Web3

def verify_transaction_signature(signed_transaction):
    # Parse the signed transaction
    tx = Web3().eth.account.decode_transaction(signed_transaction)

    # Extract the message hash and signature
    message_hash = encode_defunct(hexstr=tx.hash.hex())
    signature = tx.signature.hex()

    # Recover the address from the signature
    recovered_address = Account.recover_message(message_hash, signature=signature)

    # Compare with the 'from' address in the transaction
    if recovered_address == tx['from']:
        # Signature is valid
        return True
    else:
        # Invalid signature
        return False