Module 19: Blockchain Wallets
The wallet instance that the Wallet function creates is often called ______________, because it can be utilized with more than one blockchain provider or cryptocurrency
"universal"
Show the code for setting the gas price strategy
# Set the gas price strategy w3.eth.setGasPriceStrategy(medium_gas_price_strategy)
What code do we use to generate our HD wallet?
-call the function Wallet() -pass this function our mnemonic variable -save the HD wallet that we generated as a new variable named wallet wallet = Wallet(mnemonic) wallet
What other basic operations does EthereumTesterProvider allow us to perform?
-can use pre-populated mock accounts to test transactions -We can view the account addresses that are associated with our mock blockchain by calling w3.eth.accounts --> print(w3.eth.accounts) -fetch the corresponding account balance --> w3.eth.get_balance("0xaBbACadABa000000000000000000000000000000")
What is the structure of the ethereum account addresses?
-each address contains 42 characters -the first two characters ("0x") indicate to programs or APIs that what follows is a hexadecimal (Links to an external site.) number. The next 40 characters in the address are the last 40 characters of a hashed key that is associated with a participant's account Example: '0xABbacaDabA000000000000000000000000000009'
What are the required parameters for web3.eth.sendTransaction? (helps create and send ether-based transactions)
-from: The 42-character Ethereum account address from which the transaction is sent. -to: The 42-character Ethereum account address to which the transaction is sent. -gas: An integer representing the maximum units of gas to be used in mining the transaction. (Max units a sender is willing to spend. A standard ether transfer requires at least 21,000 units of gas.) Any unused gas will be returned to the sender -value: An integer representing the amount of money, in wei, that this transaction will transfer from the sender to the recipient
To instantiate the transaction object "raw_tx", we just need to define which two additional required data attributes?
-gasPrice: value of 0 b/c we are using a Ganache blockchain to test this transaction. If we were using a blockchain on the Ethereum network, we would instead use the value w3.eth.generateGasPrice (based on supply and demand). The gasPrice is quoted in gwei. The actual fee charged for the transaction will equal the number of gas units required to mine the transaction multiplied by the current gasPrice when the transaction is mined. -nonce: value of w3.eth.getTransactionCount(account.address). In this case, the nonce is the number of transactions sent from the specified account address
When connecting to Ganache, the code is similar to the previous lesson. Share the code/steps
-imports -mnemonic -wallet -derive_account -account number, privateKeyToAccount -check the wei balance, w3.eth.getBalance -convert to ether, w3.fromWei(wei_balance, "ether")
Which 2 new modules do we need to import for signing transactions with Web3.py?
-middleware (manages communication between the program and the Ethereum client to allow our program to run successfully) -medium_gas_price_strategy (links to an API associated with the Web3.py library that helps us to configure the gas price associated with a transaction) from web3 import middleware from web3.gas_strategies.time_based import medium_gas_price_strategy
How do we convert the integer representation of our account balance from wei to ether?
-use this built-in method: w3.fromWei -save the result of our w3.eth.get_balance call as a variable named balance. Then, we'll pass balance, and a value of "ether" for the denomination to convert to, to the w3.fromWei method balance = w3.eth.get_balance("0xaBbACadABa000000000000000000000000000000") w3.fromWei(balance, "ether")
What variables do we need to specify to create our transaction?
-value: of money we'll send. Must be given in the denomination of wei. -receiver: specify where to send our transaction amount = .0001 <--- in ether value = w3.toWei(amount, "ether") receiver = "0x4b0d14BDD1E41dAdD15B66EEB7D7c454aD19A0af"
Where do we save our seed phrase?
.env file
List the steps of adding a transaction to the Ethereum blockchain
1. Blockchain participants create transactions. 2. Miners bundle transactions waiting in the mempools into new blocks. 3. Miners compete to complete proof of work and mine new blocks. 4. A successful miner sends the new block around the network for validation, and receives a block reward. 5. The new block is linked to the blockchain. 6. All blockchain nodes update their copies of the ledger with the new block. 7. The transaction has been inalterably written onto the blockchain.
List the steps and code for what sending a transaction looks like
1. Set the sender and receiver address: sender = '0xabBACadaBA000000000000000000000000000003' receiver = '0xabbAcADABa000000000000000000000000000004' 2. Set the units of gas: gas = 21000 3. State the value and convert from ether to wei: value = w3.toWei(200, 'ether') 4. Send the transaction to the blockchain w3.eth.send_transaction({'to': receiver , 'from': sender , 'gas': gas, 'value': value})
What are the steps for generating a seed phrase with BIP-39
1. Use the function os.getenv to check our environment for the environment variable MNEMONIC 2. Save the contents stored in the .env file's MNEMONIC variable to a program variable named mnemonic 3. Use an if statement to check if mnemonic is None (if not None, we will print the contents of the variable. If None, we'll generate a new mnemonic by calling the function Mnemonic and passing it the string "english". We'll save the function as a variable named mnemo. 4. Then, on the mnemo variable, we will call the function generate and pass it a parameter of strength=128 to generate a new 12-word seed phrase. (Note that the parameter strength=256 would generate a 24-word seed phrase.) Save this as a new variable named mnemonic. 5. Print out the value of the mnemonic variable. This will return our newly generated mnemonic seed phrase.
What are the steps for using the EthereumTesterProvider?
1. create a new Web3 instance --> w3 = Web3() (the warning msg can be ignored because we want to use the "MockBackend") 2. establish a variable named provider and set it equal to an instance of the EthereumTestProvider --> provider = EthereumTesterProvider() 3. then update our Web3 instance by passing it the imported EthereumTesterProvider as a parameter --> w3 = Web3(provider) 4. Now, we can request information, such as the block number, miner, block size, and gas used for the most recent block---> w3.eth.get_block("latest")
Summarize these transaction object attributes.
1. to: Ethereum address the transaction is directed to—i.e., where we're sending our money. 2. from: Ethereum address the transaction is sent from—i.e., the sender's address. 3. value: Integer representing the value of the funds, in wei, that this transaction transfers. 4. gas: Integer representing the units of gas provided for the transaction's execution. Any unused gas will be returned to the sender. 5. gasPrice: Integer representing the estimated cost, in gwie, for each unit of gas that is needed to mine the transaction. The total transaction fee will be the actual gas price multiplied by the number of units of gas that are required to mine the transaction. Because we are using a Ganache network for testing, the gas price will be set to 0. 6. nonce: Integer of a nonce, which is determined by the number of transactions sent from a given address. The nonce allows you to overwrite your own pending transactions by using the same nonce on a new transaction.
BIP-39 includes a list of __________ words that can be included in seed phrases. To generate a seed phrase, a digital wallet typically selects either ___________ words from this list at random.
2,048 12 or 24
asymmetric cryptography
A form of cryptography that uses two separate, but mathematically related, keys for encryption and decryption; also called public key cryptography. We need a way to share confidential data without having to also share the data's password, or key. This is what asymmetric helps with.
remote procedure call (RPC)
A protocol that enables a process on one computer to call a process on another computer; when a computer program's request causes a procedure to execute on a computer or shared network at a remote location as if the request had been made locally on that computer or network. When a program is executed using the RPC model, it does not matter whether the requesting computer or network is in a different location than the executing computer or network.
key pair
A public key and private key that work together in a public encryption system.
public key
An asymmetric encryption key that does not have to be protected (i.e., bank account number: anyone with the account number—the public key—can deposit money into the account. But, withdrawing funds from the account requires not just the account number, but also the PIN—the private key)
List some popular digital wallet providers
Coinbase, Binance, and Bitfinex
T/F: Ethereum charges transaction fees based on the amount of the transaction (100 ether vs. 100,000,000 ether).
False. It is solely a supply and demand-based fee structure
List the features of a cold wallet
Hardware device Rarely connected to internet More difficult to access account information Extremely secure
Are hot or cold wallets less secure?
Hot wallets are less secure than cold wallets. This is because their internet connection can present opportunities for bad actors to access the programs, if they're not properly secured, and gain access to the stored digital keys.
If the transaction is not mined within the allotted time, what happens?
It will be returned to the sender, and they can adjust the gas price as needed to have the transaction mined.
During periods of high demand, the number of transactions sitting in an Ethereum node's mempool can exceed the number of transactions that can fit into a single block. So, how does the node's miner decide which transactions to put in a new block, and which to leave in the mempool until a later time?
Miners prioritize transactions that pay higher fees. This is because ultimately, it is more profitable for them to do so. The participant who completes proof of work first and mines a new block receives the transaction fees that are associated with all of the transactions contained within that block
Web3.py uses an ______________ provider
RPC
List the features of a hot wallet
Software or hardware device Often or always connected to internet Easier to access account information Less secure
On Ethereum, how long does this entire process of adding a block of transactions usually take?
Somewhere between 15 seconds and 5 minutes, depending on the network traffic
What does the Signed Message object consist of?
The signature itself consists of a HexBytes (Links to an external site.) hash code. And together, the r, s, and v variables that the object contains can be used to independently verify the signature.
From an Ethereum miner's perspective, why do not all transactions in the mempool have equal priority?
This is because of the way that Ethereum has set up its transaction fee and payment structure.
T/F: Ethereum currently averages around five hundred transactions, and about two megabytes of data, per block. However, the number of transactions included in any given Ethereum block is dependent on the size and complexity of the transactions.
True
T/F: Some blockchain participants choose to associate multiple public keys with their private key in order to increase privacy. It is also possible for one blockchain participant to use multiple private keys. Again, some individuals do this to increase privacy and data security.
True
T/F: The wallet instance that you create in a program is not persistent. It only exists while the program is open.
True! You will need to re-create the wallet object every time you write a program that requires you to interact with a blockchain. This is why it is important to save your mnemonic to a .env file and re-create your wallet instance with the same mnemonic each time. In effect, your mnemonic seed phrase is the master key to your wallet, and ultimately, your blockchain account.
How do we calculate the gas estimate?
We call w3.eth.estimateGas. We'll pass it an object constructed with our variables. This will return a value for our gas estimate, which we'll save as a variable named gasEstimate. # Calculate the gas estimate gasEstimate = w3.eth.estimateGas( {"to": receiver, "from": account_address, "value": value } )
Before we configure our gasEstimate, what do we have to do?
We first have to set a gas price strategy. The setGasPriceStrategy function from Web3.py constructs a strategy that will compute a gas price such that the transaction is likely to be mined within a specific amount of time. The gas price is computed by reviewing the gas prices of the most recently mined blocks.
How do you calculate the gas fee for a given transaction?
We multiply the units of gas that are required to validate the transaction by the price of each gas unit. The price of gas fluctuates based on network traffic. During periods of high demand, gas prices increase
What do we use the "Account.privateKeyToAccount" function for?
We pass it to our private key as an argument. This will return a new Ethereum account object, which we'll assign to a variable named account. The account object will allow us to send transactions to the Ethereum blockchain using our private key. account = Account.privateKeyToAccount(private)
What function do we use to sign our message?
We'll use the w3.eth.account.sign_message function to sign our message. This function accepts our message as the first argument and our private key as an argument named private_key. signed_message = w3.eth.account.sign_message(message, private_key=private) signed_message
Is there more than one transaction per block?
Yes. On the Ethereum blockchain, once a transaction enters a mempool, a miner bundles it with many other transactions that are waiting in the mempool. These are typically transactions that were created on the network around the same time. The miner then writes all of the bundled transactions into the same new block on the chain.
ether
a cryptocurrency native to Ethereum
hot wallet
a digital wallet that connects to the internet directly through a computer or cell phone. A hot wallet can be a software application on your phone or computer, or it can be a hardware wallet that connects to the internet via the USB port on your computer
Web3.py
a library that allows us to talk to Ethereum nodes in our favorite language, Python. Web3.py is a software development kit (SDK) like any other SDK you've used to talk to other APIs. But this time, the API originates from an Ethereum node.
digital signature
a mechanism for identifying participants in a blockchain and associating those identities with transactions; proves that the person authorized a given transaction on the blockchain
personal blockchain
a private blockchain that is stored on a user's local machine; useful for development and testing. Ganache is software that allows you to easily create a personal Ethereum blockchain to use for development and testing.
Bitcoin improvement proposals (BIPs)
a proposed standard that would alter current Bitcoin protocols or processes. New BIPs are voted on by the Bitcoin blockchain community. If a majority favors the BIP, it is adopted and implemented. BIPs can include changes to the process of validating transactions within the Bitcoin ecosystem, or improvements to the core process of running the Bitcoin ecosystem. Like many aspects of Bitcoin, many BIPs are also adopted by other blockchains, including Ethereum.
byte string
a series of encoded characters, or bytes, that are readable only by the computer. The byte string is identified by the "b" preceding the string
Truffle Suite
a set of tools for developers who are using the Ethereum Virtual Machine; Ganache is part of it
cryptocurrency wallet
a software program or physical hardware device that securely stores and manages a blockchain participant's payment information; This includes the participant's private key, as well as their cryptocurrency balance. The wallet also allows the participant to make cryptocurrency transactions on a blockchain.
mnemonic seed phrase
a string of randomly selected words that is used to generate a private key. (Generating a private key from a random string of words enhances the security of the private key by making it harder to guess. It also makes it harder to lose your private key)
mempool
a waiting area for the transactions that haven't been added to a block and are still unconfirmed; the network holds the transaction in a waiting area inside the memory of the network's nodes
glacial_gas_price_strategy
aims to have a transaction mined within one day
slow_gas_price_strategy
aims to have a transaction mined within one hour
fast_gas_price_strategy
aims to have a transaction mined within one minute
medium gas price strategy
aims to have the transaction mined within five minutes
EthereumTesterProvider
allows us to simulate interactions with an Ethereum blockchain (this means that we don't have to run our own blockchain or blockchain nodes in order to test code that interacts with the Ethereum blockchain; we will interact with a "mock" blockchain that the ethereum-tester library and the EthereumTesterProvider makes available)
Ganache
an application that launches a personal blockchain for the development and testing of applications designed for use on the Ethereum blockchain. It allows a user to develop, deploy, and test their decentralized applications in a safe environment
procedure call
an instruction to a computer to execute a process, or a procedure
blockchain transaction
any action that is performed on the data in the ledger—that is, any action that adds new data to the ledger
hierarchical deterministic wallets (HD wallets)
automatically generate the public-private key pair from the seed phrase, rather than having the user do it manually
Once the transaction has been created and authorized from within the wallet, it is sent to the ___________________. Then, as you know, it waits in the __________________ to be validated by a miner and added to a new block on the chain.
blockchain mem-pool
The derive_account code will return our private key in the form of a ___________________
byte string
data at rest
data that is not moving across a network; we often use one password/key to protect it; whoever knows the password can login and access the information
What function do we call to generate the public-private key pair that we will use to transact on the Ethereum blockchain?
derive_account function. The derive_account function uses the mnemonic seed phrase that is stored in the wallet object instance to generate a public-private key pair. The string "eth" associates this private-public key pair with the Ethereum blockchain. private, public = wallet.derive_account("eth")
BIP-44
derives a private key from our seed phrase; will convert the seed phrase to a corresponding private key that we can use to authorize transactions on a blockchain network; Most blockchains now use BIP-44 as the standard for generating public-private key pairs; allows a single wallet to handle multiple coins, multiple accounts, and even multiple public-private key pairs
Symmetric cryptography
essentially means that for one lock, there is one key. This one-to-one relationship provides the symmetry.
There are 1,000,000,000,000,000,000 wei in one _________
ether
RPC provider
facilitates the connection and communication between our computers and the Ethereum blockchain network. Web3.py comes bundled with several default providers
transaction fee
fee to offset the energy costs of mining transactions; charged every time a participant records a new transaction onto the chain
What is the code for the web3 and Ethereum Tester imports?
from web3 import Web3 from web3 import EthereumTesterProvider
What two more imports do we need to sign and verify messages with Web3.py?
from web3.auto import w3 from eth_account.messages import encode_defunct
What are the imports for creating an Ethereum account?
import os from dotenv import load_dotenv load_dotenv() from mnemonic import Mnemonic from bip44 import Wallet from web3 import Account
Once the block with the new transactions has been mined, what happens?
it is sent across the rest of the network for validation and is added to the ledger
Show the code for generating a seed phrase with BIP-39
mnemonic = os.getenv("MNEMONIC") if mnemonic is None: mnemo = Mnemonic("english") mnemonic = mnemo.generate(strength=128) display(mnemonic) (** Copy the displayed phrase into our .env file, so that the next time this notebook is run from the beginning, it uses this same phrase for our wallet)
What code do we use to save a message?
msg Example: msg = "Zach owes David $20" Now that we've written our message, we need to encode it from a text format into a byte format. In a byte format, the message can be read by computers and signed by our private key.
gas fee
name for Ethereum's transaction fee
The size of a mempool can vary depending upon the __________________________
network traffic
Ideally, we will only generate a seed phrase ____________
once; this seed phrase will eventually generate our private key, and we do not want to create a new seed phrase and new private key every time we run our program. That would be equivalent to wiping our wallet. Generating and storing a new seed phase would overwrite the seed phrase that preceded it—and that would also overwrite our private key.
Remember that the digital wallets that we create in our Jupyter notebooks are not persistent like physical wallets. These digital wallets get deleted every time we close the program. However, mnemonic seed phases are ________________
persistent. (we can transfer the same mnemonic seed phrase from program to program by using a .env file. Once we import our seed phrase, we can use it to re-create the same public-private key pair—and therefore, the same account information—every time we create a wallet and an account that access the Ethereum blockchain)
In the context of cryptocurrency, you use your ___________ key to send funds, ensuring that no one else can access the money in your account. You use your _________ key to receive funds.
private public
Each participant on the blockchain has one _____________ key
private (They use this private key to sign documents, messages, or transactions that they send to the blockchain—in other words, to authorize transactions. Never share it with anyone!)
The same private key can be used across multiple blockchains, if the blockchains use the same _______________
protocols (For example, a blockchain participant could use the same private key for their accounts on both Bitcoin and Ethereum)
When a blockchain participant signs a transaction with her private key, it generates a ___________ key that appears as a publicly viewable digital signature on the transaction
public (Only the private key can generate the public key. So other blockchain participants can independently verify the public key and be sure that she authorized the transaction)
cold wallets
rarely, if ever, connects to the internet. The keys it stores are completely disconnected from the digital world, except in the rare moments when they are used to withdraw or transact with the participant's funds. This makes these wallets extremely difficult for bad actors to tamper with. Several providers of hardware wallets exist, including Ledger, Trezor, and KeepKey.
What is the complete code for our transaction object?
raw_tx = { "to": receiver, "from": account_address, "value": value, "gas": gasEstimate, "gasPrice": 0, "nonce": w3.eth.getTransactionCount(account.address) }
What results when we call "account.address" and print the result?
returns a new Ethereum address that other blockchain participants can use to send us funds. In Ethereum, an account address is a shortened version of the participant's public key. print(account.address)
BIP-39
sets a standard for using a mnemonic phrase, or seed phrase, which serves as a backup that can recover your private key if your wallet is compromised, lost, or destroyed
On Ethereum blockchains, a participant's account address is a _________________ version of their public key.
shortened
Hardware wallets
store the cryptographic keys inside of a special chip
Ethereum's transaction fee depends on what?
the amount of computational power—or gas—that is required to validate the transaction and add it to a block
ephemeral blockchain
the blocks it creates are retired as soon as the purpose of recording the transaction is completed. This is ideal for testing purposes, because it means Ganache is both fast and lightweight
network traffic
the number of transactions that network participants are generating at any given time
If the gas estimate exceeds the actual cost of the gas, then what happens?
the unused gas will be returned.
What makes blockchain transactions so useful?
their ability to not just track transfers of value but also validate and store any arbitrary information within the ledger (i.e., store entire contracts or programs within a blockchain transaction)
What extra import do we need when connecting to Ganache?
w3 = Web3(Web3.HTTPProvider('HTTP://127.0.0.1:7545'))
How do we validate this transaction's signature against our public key?
we'll call w3.eth.account.recover_message(). We'll pass this function our original encoded message, as well as the digital signature contained within our SignedMessage object. This will return the account address of the participant who signed the message. w3.eth.account.recover_message(message, signature=signed_message.signature)
How do we encode our message?
we'll use the encode_defunct function that we imported. We'll pass our msg to the function as the text argument, and save it as a new variable named message: message = encode_defunct(text=msg)
The function get_balance always returns the account balance in __________
wei (the smallest denomination of ether; like being given the price of a car in pennies