How to Mine Ethereum Locally with Geth
Now that we have some accounts, we can earn ETH by running a miner.
Now that we have an account, let's play with it.
So far we've been running geth
commands from our shell, but geth
actually comes with a console of it's own. We can run this with the console
command:
./bin/geth --datadir=./datadir console
This console is a JavaScript console! That means we can write functions, perform calculations, etc. There are also a number of libraries, pre-installed, that we can use to interact with Ethereum.
The first one is simply called eth
. We can view our list of accounts like this:
eth.accounts
Ether is the currency of Ethereum. If we want to find out how much ether we have, we call eth.getBalance
:
eth.getBalance("abcxyz")
We don't have any ether yet, so it just says zero. And this brings up an interesting question: Where does ether come from in the first place?
Ether is created as a reward for mining new blocks. Again, we'll talk later about how mining works, technically, but loosely, when we want to send ether to someone else
- we create a transaction
- these transactions are grouped into blocks
- miners verify that these blocks are valid and then
- they are rewarded ether for doing this
The key idea is this: the ether is created out of thin air! This is another example of consensus -- we all just agree that miners get to create ether to give themselves a reward for doing their job.
So we can get ether by being a miner ourselves. To do this, we'll call miner.start
:
miner.start(1)
When you call this, you might need to wait a few seconds before you see "Successfully sealed a new block". Let it run for a bit and then stop the miner:
miner.stop()
You can find out the number of blocks we mined by calling eth.blockNumber
:
eth.blockNumber
Every block we mined will have earned us a certain number of ether as a reward. This reward will go to the account address we setup earlier. (Your mining destination address is sometimes called your "etherbase" address).
Let's find out how much ether we earned:
# first let's lookup our accounts
eth.accounts
# this is javascript, so we can also do this:
eth.accounts[0]
# now instead of copying and pasting our address we can use that in getBalance
eth.getBalance(eth.accounts[0])
This is a large number! What we're actually seeing here is the number of wei we earned. Ether has a bunch of different units, with wei being the smallest. wei is like cents to dollars, except one ether is 10^18th wei. You can view the whole list of the units here, but we're only going to use wei and ether.
It would be nice if we could see this number in ether instead of wei. Thankfully we can use the fromWei
method to do this:
web3.fromWei(eth.getBalance(eth.accounts[0]), "ether")
Much better. Now we can see that we earned N ether for mining the last M blocks.
Now that we have some ether, let's spend it!