Sitemap
Block Magnates

The New Crypto Publication on The Block

HD Wallet, Multi Sig Wallet and MPC — Part 1

--

I started writing this in the midst of the New Year’s Eve fireworks in 2024. I want to dedicate this write-up to my late father. He was a junior high school mathematics teacher who taught me in his classroom for two years. He possessed the teaching skills of a college lecturer. I still remember how he explained the origin of the phi number through meticulous calculations and where the value of 22/7 came from. While other math teachers often treated these numbers as mere “tools” for calculating the area or perimeter of a circle, my father delved deeper. He also explained the uniqueness of the phi number: its decimal representation does not repeat, unlike other fractional numbers. Most fractional numbers have repeating decimals after a maximum of 9 digits, but not phi. Cryptography, a field deeply rooted in mathematics, is formulated by Ph.D. mathematicians.

Let’s dive back into cryptocurrency wallets. Just like a physical wallet holds our money and needs to be kept secure, a cryptocurrency wallet is a crucial component in the world of digital currencies. In essence, it’s similar to a public key from an asymmetric encryption key pair.

One significant distinction between blockchain and traditional financial institutions (like banks) is transparency. If you have a cryptocurrency wallet (an address), anyone can see how many cryptocurrency assets are in that wallet, but they CANNOT access it. Only those who possess the private key associated with that cryptocurrency wallet (address) can withdraw the cryptocurrency assets.

There are two types of wallets: normal wallets and HD (hierarchical deterministic) wallets. You have the option to generate your own normal wallet using the steps below. This process is similar to generating an SSH key, which means you don’t necessarily have to use services like MetaMask or other wallet providers. You can connect directly to an RPC provider, such as Infura, and create your wallet. Alternatively, you can even build your own RPC node, as I explained in my previous article about staking.

Blockchain is an open system, meaning you should and must have direct access to it. You shouldn’t be restricted by any service provider.

    # Create a new Ethereum account (wallet)
account = w3.eth.account.create()

# Display the generated account details
print("Address:", account.address)
print("Private Key:", account._private_key.hex())

An HD wallet operates slightly differently. Essentially, you can have n number of addresses controlled by one master private key. The master private key is referred to as a seed phrase. A seed phrase consists of either 12 or 24 English words, as specified by the BIP39 standard. The list of words contains more than two thousand options, making the combination of 12 or 24 words nearly infinite. The generation of addresses and private keys follows a specific path.

mnemo = Mnemonic("english")
words = mnemo.generate(strength=128) # Generates a 12 word mnemonic
seed = mnemo.to_seed(words, passphrase="YourPassphrase") # You can use an optional passphrase

def derive_wallets(mnemonic, num_wallets, derivation_path):
wallets = []
for i in range(num_wallets):
path = derivation_path.format(i)
wallet = Account.from_mnemonic(mnemonic, account_path=path)
wallets.append({
'path': path,
'address': wallet.address,
'private_key': wallet.key.hex()
})
return wallets

derivation_path = "m/44'/60'/0'/0/{}" # BIP44: Ethereum path
wallets = derive_wallets(words, 5, derivation_path) # Change 5 to however many wallets you want

for wallet in wallets:
print(wallet)

When looking at the address, it is not possible to differentiate between a normal wallet and an HD wallet. HD wallets are used by central exchanges to manage their addresses, and they also reduce the complexity of private key management. HD wallets are also used by MetaMask and cold wallets such as Trezor and Ledger. If you recall, you need to write down the seed phrase when creating a MetaMask account or initializing a cold wallet. With an understanding of wallets and private key/seed generation, you can have your own cold wallet on your computer or store it on a USB drive. While it may not be as convenient as commercial cold wallets since it requires the use of the command line, the possibility is there for you to do so.

With this understanding, you can appreciate the importance of security around the seed phrase since it serves as the master key for many wallets. The impact could be significant if it gets compromised in a large exchange or other DeFi platforms.

Get Iman Kurniawan’s stories in your inbox

Join Medium for free to get updates from this writer.

Smart contracts can also function as wallets. They can receive crypto assets. There are two types of smart contract wallets: normal wallets and multi-signature wallets, often referred to as multisig wallets. The first type operates like a normal wallet, allowing you to receive and send crypto assets, and you can add additional functions as needed.

    constructor() {
owner = payable(msg.sender);
}

receive() external payable {}

function withdraw(uint _amount) external {
require(msg.sender == owner, "caller is not owner");
payable(msg.sender).transfer(_amount);
}

A multi-signature wallet requires multiple signatures before certain transactions, typically withdrawals or transfers, can be executed.

constructor(address[] memory _owners, uint _numConfirmationsRequired) {}
function submitTransaction() public onlyOwner {}
function confirmTransaction() public onlyOwner txExists(_txIndex) notExecuted(_txIndex) notConfirmed(_txIndex) {}
function executeTransaction() public onlyOwner txExists(_txIndex) notExecuted(_txIndex) {}

The script is a pseudo-script. The wallet is more secure because it requires multiple people to approve before any transaction is executed.

MPC (Multi-Party Computation)

This is a general term, primarily used to facilitate secret-sharing computations. The secret remains with you, but you can perform computations with others. A simple example is a salary survey. Typically, we are reluctant to share our salaries, but we want to know whether our salary is above or below average compared to others. This can be achieved with Multi-Party Computation (MPC). You run the same program and connect with others, then everyone inputs their salary. The salary information stays private and is not shared with others, and the computation is performed collectively. The output is the average salary.

from mpyc.runtime import mpc

async def main():
secint = mpc.SecInt(16)

await mpc.start()

my_salary = int(input('Enter your salary: '))
our_salary = mpc.input(secint(my_salary))

total_salary = sum(our_salary)
m = len(mpc.parties)

print('Average age:', await mpc.output(total_salary) / m)

await mpc.shutdown()
Press enter or click to view image in full size
Average Salary

The salary information stays in your terminal/node, and only the computation output is shared.

Now, let’s discuss secret sharing with Shamir secret sharing. I would like to express my gratitude to HashiCorp Vault for introducing me to this fantastic algorithm. Essentially, Shamir secret sharing can divide a secret string into multiple shares, and only a few shares (any of them) are needed as a threshold to reconstruct the secret. This is done to protect the secret from loss and increase its availability.

from shamir import combine, split

def hello() -> None:
"""Split a byte-string and recombine its parts."""
secret: bytes = b"Hello, World!"
shares: int = 5
threshold: int = 3

parts: list[bytearray] = split(secret, shares, threshold)
combined: bytearray = combine(parts[:3])
print(combined.decode("utf-8"))

You can reconstruct the secret string with any 3 shared keys (any keys)

Now, let’s combine the MPC concept with Shamir secret sharing. I’m using the Python library https://mpyc.readthedocs.io/en/latest/mpyc.html#module-mpyc.thresha. Due to the complexity of this library and the mathematics behind it, I will review this in part 2.

--

--