Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 5 min read

One tampered signer shouldn't be enough. A 2-of-3 Bitcoin multisig address in dependency-free Node.js

On November 18, Ledger said tampered hardware wallets had turned up in Berlin and Dubai, part of the same campaign it has been investigating in Southeast Asia since October (The Block). Ledger's security team found an im

On November 18, Ledger said tampered hardware wallets had turned up in Berlin and Dubai, part of the same campaign it has been investigating in Southeast Asia since October (The Block). Ledger's security team found an implant that captures the 24-word recovery phrase during setup and sends it out over LTE through a provisioned eSIM. According to Ledger, the secure element and the firmware were not modified, and transactions were not altered (The Block, October 13).

From a threat-model point of view this is a clean bypass. The signer's cryptography is intact. The attacker simply learns the seed at the only moment it leaves the chip in readable form, which is when the device displays it for the user to write down.

Why one device is a single point of failure

With a single-signature wallet, whoever holds the seed holds the funds. If the device that generated it was tampered with before you bought it, nothing you do afterwards fixes that, short of moving to a new seed.

A multisig output changes the rule the network enforces. A 2-of-3 output can only be spent with valid signatures from two of three keys. If those keys live on devices from different vendors, bought through different channels, a single compromised device leaks one key, and one key is not enough.

The cost is extra bookkeeping. You now have three seeds to back up, plus the information needed to rebuild the wallet: all three public keys (in practice, extended public keys and derivation paths) and the threshold. Lose that and the funds can be stuck even with two good seeds. Wallet software handles most of this for you. It is still worth knowing what the address actually commits to.

What a P2WSH multisig address commits to

A native SegWit multisig address is built in three steps:

  1. Build the witness script: OP_2 <pubkey1> <pubkey2> <pubkey3> OP_3 OP_CHECKMULTISIG.
  2. Hash it with a single SHA-256. That 32-byte hash is the witness program.
  3. Encode witness version 0 plus the program as a Bech32 address (bc1q...).

Key order matters, because a different order is a different script and a different address. BIP67 fixes this by sorting the compressed keys lexicographically, so any coordinator that follows it gets the same address from the same three keys.

The script

No dependencies. Node 18+ only, using node:crypto for SHA-256 and BigInt for a curve check.

// multisig-address.mjs
import { createHash } from 'node:crypto';

const P = 2n ** 256n - 2n ** 32n - 977n; // secp256k1 field prime
const modpow = (b, e, m) => { let r = 1n; b %= m; while (e > 0n) { if (e & 1n) r = (r * b) % m; b = (b * b) % m; e >>= 1n; } return r; };

// A compressed key is 02/03 + x. It is a real point only if x^3 + 7 is a square mod P.
function checkPubkey(hex) {
  if (!/^0[23][0-9a-fA-F]{64}$/.test(hex)) throw new Error(`not a 33-byte compressed public key: ${hex}`);
  const x = BigInt('0x' + hex.slice(2));
  if (x >= P) throw new Error(`x is outside the field: ${hex}`);
  const rhs = (x ** 3n + 7n) % P;
  if (modpow(rhs, (P - 1n) / 2n, P) !== 1n) throw new Error(`x is not on secp256k1: ${hex}`);
  return Buffer.from(hex, 'hex');
}

// Bech32 (BIP173), witness version 0
const CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
const GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
function polymod(values) {
  let chk = 1;
  for (const v of values) {
    const top = chk >>> 25;
    chk = ((chk & 0x1ffffff) << 5) ^ v;
    for (let i = 0; i < 5; i++) if ((top >>> i) & 1) chk ^= GEN[i];
  }
  return chk >>> 0;
}
const hrpExpand = (hrp) => [...hrp].map((c) => c.charCodeAt(0) >> 5).concat([0], [...hrp].map((c) => c.charCodeAt(0) & 31));
function convertBits(data, from, to) {
  let acc = 0, bits = 0; const out = []; const maxv = (1 << to) - 1;
  for (const b of data) { acc = (acc << from) | b; bits += from; while (bits >= to) { bits -= to; out.push((acc >> bits) & maxv); } }
  if (bits > 0) out.push((acc << (to - bits)) & maxv);
  return out;
}
function segwitAddress(hrp, version, program) {
  const data = [version, ...convertBits(program, 8, 5)];
  const mod = polymod([...hrpExpand(hrp), ...data, 0, 0, 0, 0, 0, 0]) ^ 1;
  const checksum = [...Array(6)].map((_, i) => (mod >>> (5 * (5 - i))) & 31);
  return hrp + '1' + [...data, ...checksum].map((d) => CHARSET[d]).join('');
}

// OP_m <key1> <key2> <key3> OP_n OP_CHECKMULTISIG, keys sorted per BIP67
function multisigScript(m, keys) {
  if (m < 1 || m > keys.length || keys.length > 16) throw new Error('need 1 <= m <= n <= 16');
  const sorted = [...keys].sort(Buffer.compare);
  const parts = [Buffer.from([0x50 + m])];
  for (const k of sorted) parts.push(Buffer.from([k.length]), k);
  parts.push(Buffer.from([0x50 + keys.length, 0xae]));
  return { script: Buffer.concat(parts), sorted };
}
const sha256 = (b) => createHash('sha256').update(b).digest();

The full file adds a small CLI and a --selftest flag. The self-test checks the encoder against the official P2WSH test vector from BIP173, checks that a key whose x is not on the curve gets rejected, and checks that shuffling the keys doesn't change the address.

Running it

$ node multisig-address.mjs --selftest
PASS BIP173 P2WSH vector
PASS rejects an x that is not on the curve
PASS key order does not change the address

With three example keys (the public keys for private keys 1, 2 and 3, which are well known and must never hold funds):

$ node multisig-address.mjs \
  0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798 \
  02C6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5 \
  02F9308A019258C31049344F85F89D5229B531C845836F99B08601F113BCE036F9
2-of-3 P2WSH address: bc1qztp0l0rwc8846ardl02fkyrrx43p96j47scz8l7qz3vnfteqc4eqtfqwcm
witness script: 52210279be...f953ae

52 is OP_2, each 21 pushes a 33-byte key, 53 is OP_3 and ae is OP_CHECKMULTISIG.

How to use this, and how not to

Use it as a cross-check. When your wallet coordinator shows you a multisig receive address, you can rebuild it from the three public keys on an offline machine and confirm it matches. If it does, the address really requires two of those three keys, and the coordinator did not slip in a key of its own.

Don't use it to generate keys, sign anything or replace your wallet software. Real setups derive keys from extended public keys along a path (BIP48 is common for multisig), and the coordinator needs to handle that and the backups.

On the hardware side, the advice from Ledger's incident update still comes first. Buy devices from the maker or a channel you can verify. If you have doubts about a device, don't create a seed on it. And if one device in your setup turns out to be bad, move to a new set of keys generated on devices you trust.

A tampered device can still leak its seed inside a multisig. With a 2-of-3 threshold, that one seed can't move the funds alone.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.