Skill 1.2.2

Create and manage accounts and sign messages with web3.js

Key Concepts

web3.eth.accounts.create() generates a new random private key and returns an account object with its address, privateKey and functions such as signTransaction and sign. privateKeyToAccount(key) rebuilds the object from an existing key. Adding accounts to web3.eth.accounts.wallet lets contract send() calls sign locally with them. web3.eth.getAccounts(), in contrast, asks the node or wallet which accounts it manages, such as the unlocked accounts of a development node.

web3.eth.accounts.sign(message, privateKey) signs a message with the EIP-191 prefix ("\x19Ethereum Signed Message:\n" plus the length), which stops a signed message from being replayed as a transaction. web3.eth.accounts.recover(message, signature) returns the signer's address. Servers use this for passwordless sign-in: they ask the user to sign a challenge and check the recovered address. Keystore files encrypt a private key with a password (encrypt() and decrypt()).