Multi-Signature Wallet Implementation: A Beginner's Guide to M-of-N Wallets

Updated on
12 min read

TL;DR

  • A multi-signature (multisig) wallet requires M-of-N signatures for fund transfers, such as 2-of-3.
  • Bitcoin multisig relies on script-based methods (OP_CHECKMULTISIG / P2SH / P2WSH) and utilizes PSBT for partial signing. For more details, check the Bitcoin Wiki on multisignature.
  • Ethereum multisig functions via smart contracts, with frameworks like Gnosis Safe being recommended for production. Explore their features here.
  • Always test on testnets, use hardware wallets, and have robust recovery plans in place (BIP-32 HD wallets are recommended: BIP-32).

Introduction

This practical guide is tailored for beginners and developers in wallet development keen to grasp and implement M-of-N multi-signature wallets on Bitcoin and Ethereum. You will gain insights into what multisig wallets are, their importance, essential terminology, how multisig enhances on-chain security, implementation steps for both Bitcoin and Ethereum, and best practices for secure operations.

Multi-signature (multisig) wallets require multiple independent private keys to authorize a transaction. Instead of relying on a single private key to manage funds, a multisig wallet requires M signatures from N possible signers. This approach is particularly useful for shared resources like company treasuries, escrow services, DAO treasury management, and personal safety strategies by distributing keys across secure locations.

Multisig Basics: Concepts & Terminology

  • M-of-N notation: Refers to the requirement of M signatures from N keyholders. For example, a 2-of-3 wallet necessitates signatures from any two of its three owners.
  • Keypair: A private key that remains secret and its corresponding public key that is shared. Each cosigner controls a keypair.
  • Signer/Cosigner: An individual who can produce a signature using their private key.
  • Threshold: The required number of signatures, represented as M.
  • Recovery mechanism: A planned method for recovering funds in case of lost keys, such as distributed backups or social recovery schemes.
  • Signing methods:
    • On-chain vs. off-chain signing:
      • Bitcoin: Signatures are often gathered off-chain and then validated by the network once the final transaction is broadcast. Scripts enforce requirements.
      • Ethereum: Uses smart contracts for multisig logic; signatures may be collected off-chain and validated on-chain during transaction execution.
  • Types of designs:
    • Script-based: Uses Bitcoin-style scripts (OP_CHECKMULTISIG, P2SH/P2WSH) to define spending conditions.
    • Contract-based: Smart contracts in Ethereum hold funds and enforce multisig logic.

It’s crucial to distinguish between custodial and non-custodial multisig, where non-custodial means cosigners have control over their own private keys, preventing any single party from unilaterally moving funds.

How Multisig Works (Under the Hood)

Here’s a high-level flow that applies to both Bitcoin script-based and Ethereum contract-based wallets:

  1. Key generation and distribution: Each cosigner generates a keypair, preferably using hardware wallets. If utilizing HD (BIP-32), keys can be derived from seeds for structured backups.
  2. Combine public keys and create a multisig address: This can be a Bitcoin redeem script or an Ethereum smart contract deployment, enforcing that M signatures are needed.
  3. Fund the multisig address.
  4. Construct an unsigned transaction: This transaction will spend the funds from the multisig address to a designated destination.
  5. Cosigners sign the transaction (off-chain): This continues until M signatures are gathered.
  6. Submit the signed transaction: Once collected, it is sent to the network where the script or contract verifies the signatures and executes the transfer.

Bitcoin Specifics

  • Bitcoin multisig generally uses redeem scripts that validate via OP_CHECKMULTISIG. Supported address types include legacy P2SH, P2WSH for native segwit, or P2SH-P2WSH for compatibility.
  • Modern proposals such as Schnorr/MuSig offer aggregated signatures, which optimize transaction size and enhance user privacy, although many wallets still rely on OP_CHECKMULTISIG and PSBT for compatibility.

Ethereum Specifics

  • Deploy a multisig smart contract like Gnosis Safe, which stores owner addresses and defines the threshold. This contract manages the funds and mandates approval rules.
  • Transactions are typically proposed and approved off-chain, with owner confirmations validated on-chain. The contract verifies approvals before executing the desired action.

Comparison: Bitcoin vs. Ethereum Multisig

AspectBitcoin (script-based)Ethereum (contract-based)
EnforcementScript validation at spending (OP_CHECKMULTISIG or Schnorr)Smart contract logic validates approvals and executes calls
Address typeP2SH / P2WSH / P2SH-P2WSHContract address (deployed bytecode)
Signature aggregationEmerging (Schnorr/MuSig)Off-chain signatures possible; contract verifies multiple signatures
FlexibilityFixed rules in scriptsHighly flexible: allows arbitrary calls, modules, and extensions (e.g., Safe modules)
UpgradeabilityGenerally non-upgradeable (scripts are immutable)Potentially upgradeable if the design allows it (with governance)
Recommended toolsPSBT compatible wallets, hardware signersGnosis Safe, OpenZeppelin, Safe SDK

Implementing Multisig on Bitcoin

The key concepts include utilizing PSBT (BIP-174) for interoperable partial signing workflows and preferring segwit (P2WSH) for lower fees. Testing should always be conducted on the testnet.

Tools & Libraries:

  • bitcoin-core (full node and RPC)
  • bitcoinjs-lib (JavaScript)
  • Electrum (desktop wallet with multisig support)
  • Hardware wallets: Trezor, Ledger
  • PSBT (BIP-174) for portable partial signing

High-Level Steps (2-of-3 Example):

  1. Generate three keypairs, with each cosigner creating keys locally—ideally using hardware wallets. Optionally implement BIP-32 HD wallets for better management.
  2. Share public keys among cosigners (never share private keys).
  3. Generate a multisig redeem script: OP_2 <pk1> <pk2> <pk3> OP_3 OP_CHECKMULTISIG.
  4. Create a P2WSH address or P2SH-P2WSH from the redeem script and fund it.
  5. When spending, create an unsigned transaction that spends the UTXO(s) from the multisig address to designated destinations.
  6. Prepare a PSBT containing the unsigned transaction and redeem script info.
  7. Each cosigner loads the PSBT into their wallet/hardware and signs—it will accumulate the required signatures.
  8. Once M signatures are present, finalize the PSBT and broadcast the transaction.

Pseudocode Example (high-level using bitcoinjs-lib-like APIs):

// Pseudocode — high-level
const pubkeys = [pk1, pk2, pk3];
const m = 2;
const redeemScript = createMultisigRedeemScript(m, pubkeys);
const p2wshAddress = createP2WSHAddress(redeemScript);

// Fund p2wshAddress on testnet

// Create PSBT
let psbt = new PSBT({ network: testnet });
psbt.addInput({ hash: utxo.txid, index: utxo.vout, witnessUtxo: utxo.output, redeemScript: redeemScript });
psbt.addOutput({ address: destination, value: amount });

// Each signer loads PSBT and signs
psbt.signInput(0, signer1KeyPair);
psbt.signInput(0, signer2KeyPair);

// Finalize & extract
psbt.validateSignaturesOfInput(0);
psbt.finalizeAllInputs();
const rawTx = psbt.extractTransaction().toHex();
// Broadcast rawTx via RPC or explorer API

Recommendations:

  • Utilize PSBT to allow cosigners with varying wallet software to collaborate.
  • Favor P2WSH (segwit) for reduced fees and enhanced signature handling.
  • Use P2SH-wrapped P2WSH for older wallet compatibility.
  • Always conduct tests on the Bitcoin testnet or regtest prior to going live.

For detailed Bitcoin multisig specifics, see the Bitcoin Wiki.

Implementing Multisig on Ethereum

Multi-signature on Ethereum operates through smart contracts. The leading choice for production environments is Gnosis Safe, which is an audited, feature-rich multisig smart contract and toolbox: Gnosis Safe Documentation.

Design Patterns:

  • Simple multisig: A basic contract that holds owners and threshold—suitable for simple scenarios but often limited in UX.
  • Gnosis Safe: Widely utilized, audited, and comes with support for modules, relayers, batching, and better UX.

Pros and Cons of On-Chain Multisig:

  • Pros: Flexibility for calling arbitrary contracts, managing complex governance logic, and integration with DeFi.
  • Cons: Potentially fatal contract bugs; gas costs for execution rely on contract security and thorough audits.

High-Level Flow (Gnosis Safe/generic):

  1. Deploy the multisig contract or instantiate it using a factory; set owner addresses and threshold M.
  2. To propose a transaction, create a transaction payload (to, value, data) and either submit it on-chain or propose it off-chain.
  3. Owners sign the transaction off-chain (using EIP-712 signatures) or confirm on-chain through transactions.
  4. After reaching the required M confirmations/signatures, execute the transaction by invoking the contract’s execute method; the contract will verify signatures and carry out the request.

Example with Gnosis Safe SDK (pseudocode):

// Pseudocode using Safe SDK + ethers.js
const safe = await Safe.create({ ethAdapter, safeAddress });
const safeTx = await safe.createTransaction({ to: destAddress, value: '0', data: txData });
const signed = await safe.signTransaction(safeTx); // cosigner signs off-chain
// After the threshold is met
const executeTxResponse = await safe.executeTransaction(safeTx);
await executeTxResponse.transactionResponse.wait();

Practical Recommendations:

  • Use Gnosis Safe for production to benefit from its security features, SDKs, and user-friendly experience (Gnosis Safe Documentation).
  • Remain mindful of gas costs; consider employing relayers or transaction batching for enhanced UX.
  • Plan upgradeability judiciously; immutable contracts can reduce risks, but planned upgradeability may be necessary for critical patches—only implement if governance and audits are in place.

Security Considerations & Best Practices

  • Setting the threshold: A higher M increases security (more signers are needed) but may hinder availability. Select a threshold reflecting your operational model; for instance, a 2-of-3 configuration is typical for smaller teams, while a 3-of-5 is often preferable for larger treasuries.
  • Key Management:
    • Employ hardware wallets (like Ledger or Trezor) and air-gapped signers when feasible.
    • Keep encrypted backups of keys and distribute them in secure locations.
    • Utilize HD wallets (BIP-32) to simplify your backup strategies: BIP-32.
  • Recovery Plans:
    • Prepare for lost signers by creating replacement procedures, pre-designated emergency signers, or social recovery schemes if appropriate.
    • Regularly conduct recovery drills using testnets to ensure preparedness.
  • Mitigating Malicious Signers:
    • Consider incorporating time locks or multi-stage approval processes for added security.
    • Implement off-chain policies, audits, and monitoring to minimize insider risks.
  • Smart Contract Risk:
    • For Ethereum, opt for audited and well-reviewed contracts like Gnosis Safe.
    • Avoid deploying custom multisig contracts in a production environment unless they have undergone thorough scrutiny and formal verification.
  • Operational Security (OpSec):
    • Limit the exposure of public keys to only what’s necessary.
    • Establish alerts for significant outgoing transactions and multisig activity.
    • Publish security contact information following the best practices detailed in our Security.txt File Setup Guide.

Testing, Deployment & Maintenance

  • Conduct thorough testing on testnets (Bitcoin testnet/regtest for Bitcoin; Ropsten/Goerli or local Hardhat for Ethereum).
  • Simulate failure conditions such as lost signers, offline signers, corrupted PSBTs, and malicious signer encounters.
  • Automate testing protocols: unit tests for smart contract logic and integration tests verifying the entire signing process.
  • Set up monitoring to detect alerts for large outgoing transactions and any unusual activities.
  • Establish governance and upgradeability protocols, documenting upgrade paths, governance roles, and transparently publishing upgrade proposals.

Common Pitfalls & Troubleshooting

  • Compatibility Issues: Ensure that all cosigners utilize compatible address types (P2SH vs. P2WSH) and versions of PSBT.
  • Redeem Script/Address Mismatch: Verify redeem script hashes; discrepancies can prevent fund spending.
  • Improperly Serialized Transactions: Utilize PSBT libraries and validate signatures before broadcast.
  • Lost Keys Without Recovery: Maintain tested backups and rehearse recovery processes regularly.

Troubleshooting Checklist:

  • Verify that redeem script hash aligns with the on-chain scriptPubKey.
  • Ensure the PSBT encompasses the complete redeem/witness scripts for all inputs.
  • Test the signing sequence on the testnet involving all cosigners.

Practical Example / Mini Walkthrough

2-of-3 Bitcoin PSBT Implementation (High-level):

  1. Cosigner A, B, and C each generate a keypair and exchange public keys.
  2. Build a 2-of-3 redeem script and derive a P2WSH address.
  3. Fund the address on testnet.
  4. Create a PSBT referencing the UTXO and redeem script.
  5. Cosigner A signs the PSBT, exports it, and sends it to Cosigner B.
  6. Cosigner B signs; the PSBT now contains two signatures.
  7. Finalize and broadcast the transaction.

2-of-3 Ethereum Implementation (Gnosis Safe Flow - High-level):

  1. Deploy a Safe with owners [A, B, C] and set a threshold of 2.
  2. Propose a transaction (for sending ETH or contract invocation) via the Safe UI or SDK.
  3. Owner A signs the proposal off-chain. Owner B then signs as well.
  4. Once two signatures are collected, execute the transaction through the Safe’s execute method; the Safe contract will verify signatures and perform the call.

Starter Repositories & Tools:

  • Gnosis Safe SDK and documentation: Gnosis Safe
  • bitcoinjs-lib examples and PSBT utilities
  • Electrum multisig documentation and tutorials

Conclusion & Further Resources

Multi-signature wallets are an effective means of enhancing security and distributing control over crypto assets. For Bitcoin, implement PSBT workflows, prefer segwit P2WSH, and perform tests on the testnet. For Ethereum, prioritize audited solutions like Gnosis Safe in production environments. Rigorous planning for key management, backups, and recovery is essential alongside the adoption of hardware wallets and contract code audits.

  • Explore implementing a 2-of-3 multisig on testnets for both Bitcoin and Ethereum.
  • Delve into advanced topics, such as Schnorr/MuSig enhancements for Bitcoin or Safe modules for Ethereum.

References and Further Reading:

Pre-Launch Checklist Before Going Live on Mainnet:

  • Test the complete flow on the testnet with all cosigners.
  • Validate the execution flow of PSBT or Safe end-to-end.
  • Make use of hardware wallets and ensure unique secured backups for all seeds.
  • Document recovery procedures and incident response strategies thoroughly.
  • If utilizing contracts, confirm audits have been conducted and maintain careful upgrade plans.
TBO Editorial

About the Author

TBO Editorial writes about the latest updates about products and services related to Technology, Business, Finance & Lifestyle. Do get in touch if you want to share any useful article with our community.