2018-03-24 21:24:20 +00:00
|
|
|
import { LegacyWallet } from './legacy-wallet';
|
|
|
|
const bitcoin = require('bitcoinjs-lib');
|
2018-03-20 22:41:07 +02:00
|
|
|
|
|
|
|
export class SegwitBech32Wallet extends LegacyWallet {
|
2018-12-28 16:52:06 +01:00
|
|
|
static type = 'segwitBech32';
|
|
|
|
static typeReadable = 'P2 WPKH';
|
2018-03-20 22:41:07 +02:00
|
|
|
|
|
|
|
getAddress() {
|
|
|
|
if (this._address) return this._address;
|
|
|
|
let address;
|
|
|
|
try {
|
|
|
|
let keyPair = bitcoin.ECPair.fromWIF(this.secret);
|
2019-09-14 07:15:59 +09:00
|
|
|
address = bitcoin.payments.p2wpkh({
|
|
|
|
pubkey: keyPair.publicKey,
|
|
|
|
}).address;
|
2018-03-20 22:41:07 +02:00
|
|
|
} catch (err) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
this._address = address;
|
|
|
|
|
|
|
|
return this._address;
|
|
|
|
}
|
2018-06-24 22:27:34 +01:00
|
|
|
|
|
|
|
static witnessToAddress(witness) {
|
|
|
|
const pubKey = Buffer.from(witness, 'hex');
|
2019-09-14 07:15:59 +09:00
|
|
|
return bitcoin.payments.p2wpkh({
|
|
|
|
pubkey: pubKey,
|
|
|
|
network: bitcoin.networks.bitcoin,
|
|
|
|
}).address;
|
2018-06-24 22:27:34 +01:00
|
|
|
}
|
2019-01-05 20:23:51 +00:00
|
|
|
|
2019-09-22 14:37:23 +01:00
|
|
|
/**
|
|
|
|
* Converts script pub key to bech32 address if it can. Returns FALSE if it cant.
|
|
|
|
*
|
|
|
|
* @param scriptPubKey
|
|
|
|
* @returns {boolean|string} Either bech32 address or false
|
|
|
|
*/
|
2019-01-05 20:23:51 +00:00
|
|
|
static scriptPubKeyToAddress(scriptPubKey) {
|
|
|
|
const scriptPubKey2 = Buffer.from(scriptPubKey, 'hex');
|
2019-09-22 14:37:23 +01:00
|
|
|
let ret;
|
|
|
|
try {
|
|
|
|
ret = bitcoin.payments.p2wpkh({
|
|
|
|
output: scriptPubKey2,
|
|
|
|
network: bitcoin.networks.bitcoin,
|
|
|
|
}).address;
|
|
|
|
} catch (_) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return ret;
|
2019-01-05 20:23:51 +00:00
|
|
|
}
|
2018-03-20 22:41:07 +02:00
|
|
|
}
|