Skip to content

Instantly share code, notes, and snippets.

@itoonx
Created March 2, 2019 21:26
Show Gist options
  • Save itoonx/339d72bfd3837e674b1f10b61464e3ec to your computer and use it in GitHub Desktop.
Save itoonx/339d72bfd3837e674b1f10b61464e3ec to your computer and use it in GitHub Desktop.
Bitcoin_MultiSig_Wallet.js
const crypto = require('crypto');
const bitcoinjs = require('bitcoinjs-lib');
module.exports = (user_id, currency_type) => {
// Generate a P2SH, pay-to-multisig (3-of-4) address
// แปลง user_id ให้เป็น string ก่อน
let shash = String(user_id);
// แปลงให้เป็น hash จะได้มี 16 byte
let hash = crypto.createHash('md5').update(shash).digest('hex');
// เอา hash 16 byte มาแปลงให้เป็นในรูปแบบ Buffer จะได้ 32 byte
let buffer = Buffer.from(hash.toString('hex'), 'utf8');
// นำ Buffer ที่มีขนาด 32 byte มาแปลงเป็น Private Key
let keyPairSeed = bitcoinjs.ECPair.fromPrivateKey(buffer);
console.log('keyPairSeed: ', keyPairSeed);
// ดึงค่าจาก Deconstructor ให้ออกมาในรูปแบบ Buffer
var { pubkey, address } = bitcoinjs.payments.p2pkh({ pubkey: keyPairSeed.publicKey });
console.log('Private Key String (WIF)', keyPairSeed.toWIF());
console.log('PublicKey String: ', pubkey.toString('hex'));
console.log('Address (ripemd-160): ', address);
let pubkeys = [
// Pubkey was generated from user_id
pubkey.toString('hex'),
// Pubkey was generated by offline wallet
'03f1cfd329a20fd9f88f0a1d615e3190dcb8c1a3a68c6f053187fc53b4bf1bb130', // Signer 1
'0349c32f6983c054cc78bcc93d44e4f086fe16c38e61a9221fe510d7e1aec9ba4f', // Signer 2
'02d52c3659b8dcc4f4cb1eb42847d2d5d295c352cbd9c0443bee18f14f21df3779' // Signer 3
].map((hex) => Buffer.from(hex, 'hex')); // แปลงให้เป็น Buffer อีกครั้งเพื่อนำไปสร้าง Redeem Signature
/** จะได้ Multisig Wallet Address มา โดยจะขึ้นต้นด้วยเลข 3 นำหน้า
* กำหนด Redeem Signature ให้ต้องการ Private Key 3 ใน 4 ตัวนี้ */
var { address } = bitcoinjs.payments.p2sh({
redeem: bitcoinjs.payments.p2ms({ m: 3, pubkeys })
})
// Save ลง Database ได้เลย ปลอดภัยแน่นวลลล !!!
let wallet = {
currency_type,
address: address,
public_key: pubkey.toString('hex'),
private_key: keyPairSeed.toWIF(),
wallet_type: 'MultiSig'
}
return wallet;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment