import * as crypto from "@node-lightning/crypto" ; import { PrivateKey } from "./PrivateKey" ; import { Script } from "./Script" ; import { Address } from "./Address" ; import { BitcoinError } from "./BitcoinError" ; import { BitcoinErrorCode } from "./BitcoinErrorCode" ; import { Network } from "./Network" ; /**
 * This class represents a point on an secp256k1 elliptic curve and acts
 * as a public key along with the network for which the key belongs. The
 * public key can be serialized into a buffer using the SEC compressed
 * and uncompressed format.
 */ export class PublicKey { param input returns public static fromWif ( input ) { const [ , pubkey ] = PrivateKey . fromWif ( input ) ; return pubkey ; } public readonly compressed : boolean ; private readonly _buffer : Buffer ; param buffer param network constructor ( buffer , readonly network ) { if ( ! crypto . validPublicKey ( buffer ) ) { throw new BitcoinError ( BitcoinErrorCode . PubKeyInvalid , { key : buffer } ) ; } this . compressed = buffer . length === 33 ; this . _buffer = buffer ; } param tweak returns public tweakAdd ( tweak ) { const result = crypto . publicKeyTweakAdd ( this . _buffer , tweak , this . compressed ) ; return new PublicKey ( result , this . network ) ; } param tweak returns public tweakMul ( tweak ) { const result = crypto . publicKeyTweakMul ( this . _buffer , tweak , true ) ; return new PublicKey ( result , this . network ) ; } param other returns public add ( other ) { if ( this . network !== other . network ) { throw new BitcoinError ( BitcoinErrorCode . NetworkMismatch , { me : this , other } ) ; } const result = crypto . publicKeyCombine ( [ this . toBuffer ( ) , other . toBuffer ( ) ] , this . compressed ) ; return new PublicKey ( result , this . network ) ; } returns public hash160 ( ) { return crypto . hash160 ( this . toBuffer ( ) ) ; } param compressed public toPubKey ( compressed ) { const buffer = crypto . convertPublicKey ( this . _buffer , compressed ) ; return new PublicKey ( buffer , this . network ) ; } returns public toBuffer ( ) { return Buffer . from ( this . _buffer ) ; } returns public toHex ( ) { return this . toBuffer ( ) . toString ( "hex" ) ; } returns public toP2pkhAddress ( ) { return Address . encodeBase58 ( this . network . p2pkhPrefix , this . hash160 ( ) ) ; } returns public toP2nwpkhAddress ( ) { return Script . p2wpkhLock ( this . hash160 ( ) ) . toP2shAddress ( this . network ) ; } returns public toP2wpkhAddress ( ) { return Address . encodeBech32 ( this . network . p2wpkhPrefix , 0 , this . hash160 ( ) ) ; } }