miguelmota / go-ethereum-hdwallet

Ethereum HD Wallet derivations in Go (golang)
https://github.com/miguelmota/go-ethereum-hdwallet
MIT License
494 stars 270 forks source link

Support for EIP155 signer #7

Closed cypherhat closed 4 years ago

cypherhat commented 5 years ago

I love this package, but I want to use it to sign token transfers as well. Which, as I understand it means that I have to us: types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey). I can PR this package, but I am unsure how you would want this implemented. THis is less than DRY, but my thought is:

// SignTxEIP155 implements accounts.Wallet, which allows the account to sign an ERC-20 transaction.
func (w *Wallet) SignTxEIP155(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
    w.stateLock.RLock() // Comms have own mutex, this is for the state fields
    defer w.stateLock.RUnlock()

    // Make sure the requested account is contained within
    path, ok := w.paths[account.Address]
    if !ok {
        return nil, accounts.ErrUnknownAccount
    }

    privateKey, err := w.derivePrivateKey(path)
    if err != nil {
        return nil, err
    }

    // Sign the transaction and verify the sender to avoid hardware fault surprises
    signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey)
    if err != nil {
        return nil, err
    }

    msg, err := signedTx.AsMessage(types.NewEIP155Signer(chainID))
    if err != nil {
        return nil, err
    }

    sender := msg.From()
    if sender != account.Address {
        return nil, fmt.Errorf("signer mismatch: expected %s, got %s", account.Address.Hex(), sender.Hex())
    }

    return signedTx, nil
}

Thoughts?

miguelmota commented 4 years ago

Closed via https://github.com/miguelmota/go-ethereum-hdwallet/pull/8