In web3 APIs I could not see an option to specify private key for sending a transaction in doc. How this is done then ? My understanding is that we need private key of a particular account to send transaction.
web3 sends transactions using unlocked wallets, which requires that you unlock your account using the keyfile and the password prior to sending a transaction. web3 is then able to access the the private key from the unlocked wallet and sign the transaction.
If you want to avoid unlocking the wallet, you need to sign the transaction yourself and send a raw transaction using eth.sendRawTransaction.
Unfortunately, web3 does not support signing of transactions. However, you can sign a transactrion using ethereumjs-tx. To obtain a hex string
serializedTx containing the signed transaction use
const tx = new EthereumTx(txParams); tx.sign(privateKey); let serializedTx = "0x" + tx.serialize().toString('hex');
serializedTx can be used with eth.sendRawTransaction.
For signing the transactions, the private key
privateKeyis needed. If you don't have the private key, you can use myetherwallet.com to obtain it from a keyfile and the passphrase, or you can optain the private key programatically from a keyfile and the password using
let privateKey = keythereum.recover(password, keyObject);
keyObject is the content of the keyfile, which is a JSON string.
The signing of the transaction is handled by the Provider set on the web3 object.
For example, if the user is interacting with a Dapp through a browser then it is likely that the provider is MetaMask and this will handle the user authorising the transactions.